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

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
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
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
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));
}

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.
The dummy + memcpy should suffice then.
I'm curious. If my answer was "just for clarity" how would you do that?
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.