I'm trying to assign multidimensional array to unitilized array in struct like this:
typedef struct TestStruct
{
int matrix[10][10];
} TestStruct;
TestStruct *Init(void)
{
TestStruct *test = malloc(sizeof(TestStruct));
test->matrix = {{1, 2, 3}, {4, 5, 6}};
return test;
}
I got next error:
test.c:14:17: error: expected expression before '{' token
test->matrix = {{1, 2, 3}, {4, 5, 6}};
What is the best way in C to assign matrix?
You cannot initialize the matrix this way. In C99, you can do this instead:
*test = (TestStruct){{{1, 2, 3}, {4, 5, 6}}};
Before C99, you would use a local structure:
TestStruct *Init(void) {
static TestStruct init_value = {{{1, 2, 3}, {4, 5, 6}}};
TestStruct *test = malloc(sizeof(TestStruct));
if (test)
*test = init_value;
return test;
}
Note that structure assignent *test = init_value;
is substantially equivalent to using memcpy(test, &init_value, sizeof(*test));
or a nested loop where you copy the individual elements of test->matrix
.
You can also clone an existing matrix this way:
TestStruct *Clone(const TestStruct *mat) {
TestStruct *test = malloc(sizeof(TestStruct));
if (test)
*test = *mat;
return test;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.