Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Statically initialize array within structure

Ain't gonna speak for other compilers, but in GNU GCC compiler you can statically initialize array with the following syntax:

struct some_struct {
        unsigned *some_array;
} some_var = {
        .some_array = (unsigned[]) { 1u, 2u, 3u, 4u, 5u, },
};

First I've met this syntax searching for the answer of a question I was concerned and came to this answer. But I've not found any link to GNU reference which covers this kind of syntax yet.

I'd be very grateful if someone share me a link on this syntax. Thank you!

like image 578
mesmerizingr Avatar asked Oct 20 '22 03:10

mesmerizingr


1 Answers

Well, if your question is about compound literal syntax, then one important detail here is that you are not initializing an array within a structure. You are initializing a pointer within a structure. The code that you have now is formally correct.

If you really had an array inside your structure, then such initialization with a compound literal would not work. You cannot initialize an array from another array. Arrays are not copyable (with the exception of char array initialization from string literal). However, in that case you'd be able to use an ordinary {}-enclosed initializer, not a compound literal.

Also keep in mind that the lifetime of the compound literal (unsigned[]) { 1u, 2u, 3u, 4u, 5u, } is determined by the scope in which it appears. If you do the above in local scope, the compound literal array will be destroyed at the end of the block. The pointer value (if you somehow manage to take it outside that block) will become invalid.

like image 50
AnT Avatar answered Nov 04 '22 00:11

AnT