Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C structure initialization? [duplicate]

How can I initialize a structure if one field in the structure is itself a structure?

like image 340
0xAX Avatar asked Jul 05 '10 05:07

0xAX


People also ask

How do you initialize a structure in C?

Structure members can be initialized using curly braces '{}'. For example, following is a valid initialization.

How do you initialize a structure?

An initializer for a structure is a brace-enclosed comma-separated list of values, and for a union, a brace-enclosed single value. The initializer is preceded by an equal sign ( = ).

How are structs initialized?

When initializing a struct, the first initializer in the list initializes the first declared member (unless a designator is specified) (since C99), and all subsequent initializers without designators (since C99)initialize the struct members declared after the one initialized by the previous expression.

Is it possible to initialize an array of structure?

It's called designated initializer which is introduced in C99. It's used to initialize struct or arrays, in this example, struct . Show activity on this post. It's a designated initializer, introduced with the C99 standard; it allows you to initialize specific members of a struct or union object by name.


1 Answers

You need to use more braces (actually, they're optional, but GCC makes a warning these days). Here's an example:

struct s1 { int a; int b; };
struct s2 { int c; struct s1 s; };

struct s2 my_s2 = { 5, { 6, 3 } };
like image 167
Carl Norum Avatar answered Sep 28 '22 09:09

Carl Norum