1

How I can initialize an element in a struct? I have this struct:

typedef struct { int mat[x][x]; int res; } graphe;
graphe g;

I was expecting this to work:

g.mat = {{0, 1}, {1, 0}, {1, 1}, {0, 1}};

but it does not.

4
  • You'll need to elaborate on what "doesn't work". Commented Oct 9, 2014 at 22:20
  • It looks like you meant: g.mat = {{{0, 1}, {1, 0}, {1, 1}, {0, 1}}};. That is, another set of braces to initialize array. Commented Oct 9, 2014 at 22:24
  • Assignment and initialization are different concepts in C. You are not initializing but assigning. Commented Oct 9, 2014 at 22:44
  • @0x499602D2 brace-enclosed initializers can't be used for assignment Commented Oct 9, 2014 at 22:46

2 Answers 2

2

The main problem is that arrays are not assignable, and by the time you want to set g.mat, it has already been default initialized. What you are attempting is to assign values to the members of an existing instance. A lesser problem is some missing braces.

Instead of default-initializing g and then attempting to assign values to its members, you can initialize the graphe object with the desired values for the members:

graphe g = {{{0, 1}, {1, 0}, {1, 1}, {0, 1}}};

This will also implicitly initialize g.res to 0, but you can also initialize it to a specific value:

graphe g = {{{0, 1}, {1, 0}, {1, 1}, {0, 1}}, 42};

Here's an example using designated initializers. This might be easier to read than the previous examples, and you can change the order of the fields:

graphe g = { .mat = {{0, 1}, {1, 0}, {1, 1}, {0, 1}}, .res = 42};
Sign up to request clarification or add additional context in comments.

Comments

1

You can initialize your g at the point of definition, as shown in @juanchopanza's answer.

However, you can also assign a new value to g later (if the need arises) by using a similar syntax in combination with the compound literal feature of C language

g = (graphe) { { { 0, 1 }, { 1, 0 }, { 1, 1 }, { 0, 1 } }, 42 };

Note that the assignment operator will only work for the entire struct object. If you want to assign a new value only to the g.mat array, not touching any other fields of g, then the assignment operator won't work for that purpose since arrays in C are not assignable. However, you can still use memcpy in combination with a compound literal to copy new values into g.mat

memcpy(g.mat, (int [x][x]) { { 0, 1 }, { 1, 0 }, { 1, 1 }, { 0, 1 } }, sizeof g.mat);

This is actually what you tried to do in your question.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.