Best way to initialize a matrix inside a struct in c.

Jun 25, 2020 at 3:12pm
Hi!

What is the best way to initialize an 2d array inside a struct in c?
I tried this but I'm getting an error message:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <stdio.h>

struct node {
	int x[3][3] = {{3, 5, 2},
		       {1, 7, 4},
		       {0, 3, 9}};
};


int main(int argc, const char *argv[])
{
	

	return 0;
}

1
2
main.c:4:14: error: expected ‘:’, ‘,’, ‘;’, ‘}’ or ‘__attribute__’ before ‘=’ token
    4 |  int x[3][3] = {{3, 5, 2},
Last edited on Jun 25, 2020 at 3:13pm
Jun 25, 2020 at 3:19pm
Since this is C you can't initialize structure variables in the structure declaration, you'll need to initialize the variable after the definition, manually.

By the way your code will compile with C++.



Last edited on Jun 25, 2020 at 3:20pm
Jun 25, 2020 at 4:16pm
I was wondering if there is a way to do that like the following code or I'll have to do like the comment one.
1
2
3
4
5
6
7
8
9
10
void init_node(struct node *n)
{
	n->x = {{3, 5, 2},
                {1, 7, 4},
	        {0, 3, 9}};

	// n->x[0][0] = 3;
	// n->x[0][1] = 5;
	// if the matrix is too large i'll have too many lines
}
Last edited on Jun 25, 2020 at 4:18pm
Jun 25, 2020 at 4:25pm
Is x the only member of the node, or is that just for clarity?

This is about the best you can manage in standard C.
1
2
3
4
5
6
7
void init_node(struct node *n)
{
    static const int dummy[3][3] = {{3, 5, 2},
                {1, 7, 4},
	        {0, 3, 9}};
    memcpy(n->x, dummy, sizeof(dummy));
}

Jun 25, 2020 at 4:34pm
Is x the only member of the node, or is that just for clarity?


Actually "struct node" has more variables including x, but the problem is the 2d array.
Jun 25, 2020 at 4:39pm
The dummy + memcpy should suffice then.
Jun 25, 2020 at 4:58pm
I'm curious. If my answer was "just for clarity" how would you do that?
Jun 25, 2020 at 7:19pm
Because then you could do
1
2
3
4
5
6
7
void init_node(struct node *n)
{
    static const node dummy = {{3, 5, 2},
                {1, 7, 4},
	        {0, 3, 9}};
    *n = dummy;
}

Topic archived. No new replies allowed.