vkoskiv
vkoskiv

Reputation: 65

Initializing matrix variable in a C struct

I have a struct as follows:

struct transform {
    double A[4][4];
};

I know I can initialize the entire struct like so:

struct transform myTransform;
myTransform = (struct transform){{{0, 0, 0, 0},{0, 0, 0, 0},{0, 0, 0, 0},{0, 0, 0, 0}}};

But why can I not do the following?

struct transform secondTransform;
secondTransform.A = {{0, 0, 0, 0},{0, 0, 0, 0},{0, 0, 0, 0},{0, 0, 0, 0}};

My logic says that makes sense. I just extend the same logic as before, but only initialize the A matrix within my struct, but I receive an ambiguous Expected expression error.

The reason I ask is, I have a more complex struct than this in my project and I would like to specifically initialize elements within that struct instead of the whole thing.

Edit: I am using the C99 standard for my project.

Upvotes: 2

Views: 71

Answers (2)

dbush
dbush

Reputation: 223972

The problem you're having is that the first case is an initialization while the second case is an assignment, and you can't assign to an array.

You can however initialize a struct without explicitly initializing all members. This is done with a designated initializer.

struct transform {
    double A[4][4];
    int b;
    char *c;
};

struct transform t = { .A = {{0, 0, 0, 0},{0, 0, 0, 0},{0, 0, 0, 0},{0, 0, 0, 0}}, .b = 5 };

Any field not explicitly initialized is implicity initialized to 0 or NULL as appropriate for the type.

Upvotes: 1

templatetypedef
templatetypedef

Reputation: 372814

There's no fundamental reason why the C compiler couldn't be designed so that it could figure out what you meant there. It just happens to be the case that C only lets you use brace initialization in certain cases, and that isn't one of them.

Upvotes: 0

Related Questions