2

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?

jl284
  • 61
  • 5
  • Arrays cannot be assigned in C. They can be initialised, but this can *only* be done on definition. – alk Jul 31 '16 at 17:46

1 Answers1

4

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;
}
chqrlie
  • 131,814
  • 10
  • 121
  • 189
  • But I want initialize matrix in Init() function, is there a way to do it via pointers? – jl284 Jul 31 '16 at 12:44
  • 1
    @JacobLutin: the various methods described above **do** initialize the matrix. What do you mean by *is there a way to do it via pointers?* – chqrlie Jul 31 '16 at 13:47