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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With