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?

1
  • Arrays cannot be assigned in C. They can be initialised, but this can only be done on definition. Commented Jul 31, 2016 at 17:46

1 Answer 1

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;
}
Sign up to request clarification or add additional context in comments.

2 Comments

But I want initialize matrix in Init() function, is there a way to do it via pointers?
@JacobLutin: the various methods described above do initialize the matrix. What do you mean by is there a way to do it via pointers?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.