Compound literal in an array definition

Consider this array:

unsigned char* array[] = { (unsigned char[5]){}, (unsigned char[5]){} };

Does array[0] and array[1] still point to a valid memory even after the complete definition of array? Meaning, afterwards I am allowed to do for example
memcpy(array + 1, "\x01\x02\x03\x04\x05", 5);

>Solution :

If that declaration appears outside of any function, then array and the compound literals have static storage duration, so they exist for the duration of program execution, and you can use them at any point in the program.

If the declaration appears inside of a function, then array and the compound literals have automatic storage duration associated with the enclosing block. Using the memory of the compound literals is defined as long as using array is defined.

Note that {} is not a strictly conforming initializer; you should give at least one value, as in {0}. (GCC and other compilers may accept {}.)

Leave a Reply