...
The storage for this object is either static if the compound literaloccurs literal occurs at file scope or automatic if the compound literal occurs at block scope (6.5.2.5.6).
E.g., after the execution of the following line, contained in some arbitrary For example, in the following function:
Code Block |
---|
void func(void) { int *iip = (int[4]){1,2,3,4}; /* ... */ } |
Wiki Markup |
---|
following initialization, the {{int}} pointer "i" would contain {{ip}} contains the address of an unnamed object of type "{{int \[4\]"}}, allocated on the stack. |
It should be noted Note that only one object is created per compound literal -- even if the compound literal appears in a loop and has dynamic initializers (6.5.2.5.16). This can lead to incorrect use, as demonstrated below.
Noncompliant Code Example
Wiki Markup |
---|
In this noncompliant code example, an the programmer mistakenly assumes that the elements of the {{ints}} array of pointerspointer is filled with what appear toto {{int_struct}} are assigned the addresses of distinct {{INTint_STRUCTstruct}} objects, one for each integer in the range \[0, MAX_INTS-1\]: |
Code Block | ||||
---|---|---|---|---|
| ||||
#include <stdio.h> typedef struct INTint_STRUCTstruct { int x; } INTint_STRUCTstruct; #define MAX_INTS 10 int main(int argc, char **argvvoid){ intsize_t i; INTint_STRUCTstruct *ints[MAX_INTS]; for (i = 0; i < MAX_INTS; i++) { ints[i] = &(INTint_STRUCTstruct){i}; } for (i = 0;i<MAX i < MAX_INTS; i++) { printf("%d\n", ints[i]->x); } } |
However, only one INTint_STRUCTstruct
object is created. At each iteration of the first loop, the x
member of this object is set equal to the current value of the loop counter i
. Therefore, after the first loop terminates, the value of the x
member is MAX_INTS - 1
.
During the print loop, this value is printed MAX_INTS times because every pointer in the "ints" array is set to point to the (single) INTint_
STRUCT struct
object.
This is contrary to the intuitive expected result, which is that the integers 0 through MAX_INTS-1 would be printed in order.
Compliant Solution
This compliant solution uses an array of structures rather than an array of pointers. That way, an actual copy of each INTint_
STRUCT struct
(rather than a pointer to the object) is stored.
Code Block | ||||
---|---|---|---|---|
| ||||
#include <stdio.h> typedef struct INTint_STRUCTstruct { int x; } INTint_STRUCTstruct; #define MAX_INTS 10 int main(int argc,char** argvvoid){ int i; INTint_STRUCTstruct ints[MAX_INTS]; for(i=0;i<MAX_INTS;i++) ints[i] = (INTint_STRUCTstruct){i}; for(i=0;i<MAX_INTS;i++) printf("%d\n",ints[i].x); } |
...