Statically initialize an array inside a structure

I am not going to speak for other compilers, but in the GNU GCC compiler you can statically initialize an array with the following syntax:

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

First, I met this syntax, looking for the answer to a question that I was interested in, and came to this . But I did not find a link to a GNU link that still supports this kind of syntax.

I would really appreciate it if someone shares me a link to this syntax. Thanks!

+5
source share
2 answers

You are unlikely to find a lot of GNU documentation because it is not a GCC extension - it is part of the standard C syntax called a composite literal. It is defined in the C standard in sections 6.5.2.5 and 6.7.9 (the latter covers the part between curly braces, which is the same for compound literals and for static initializers, so the standard describes it only once).

You can use this syntax to describe the values ​​of dynamic objects, and not just for static initializations, even standing separately in an expression without assigning any variable. A combined literal can appear almost anywhere a variable name can appear: you can pass them to functions, create them only to access one element, take their address (you can even assign them, although this is not obvious how useful this is).

The syntax is uniform across all types of C values ​​and can be used to create arrays (designate specific elements for installation with [N]= ), structures and unions (designate specific elements with .field= ), and even numeric types (without elements, therefore don't specify, just put the value between braces). The syntax should be simple and consistent for macros and code generators to create (in addition to being elegant for manual recording).

+1
source

Well, if your question is about complex literal syntax, then the important detail here is that you are not initializing the array inside the structure. You initialize the pointer inside the structure. The code you have is formally correct.

If you really have an array inside your structure, then such initialization with a composite literal will not work. You cannot initialize an array from another array. Arrays cannot be copied (except for initializing the char array from a string literal). However, in this case, you can use a regular {} -included initializer, rather than a compound literal.

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

+2
source

Source: https://habr.com/ru/post/1200244/


All Articles