Home > other >  Error with initialization of 2d arrays in C
Error with initialization of 2d arrays in C

Time:11-18

So, I have declared a typedef as:

typedef float Matrix4[4][4];

when I try to Initialize it as:

void getXRotationMatrix(float theta, Matrix4 ans) {

    ans = { {0,0,0,0},{1,1,1,1},{0,0,0,0},{1,1,1,1} };
}

it gives an error:

too many initializer values

however, it works when I initialize it as:

void getXRotationMatrix(float theta, Matrix4 ans) {

    float a[4][4] = { {0,0,0,0},{1,1,1,1},{0,0,0,0},{1,1,1,1} };
    ans = a;

}

It doesn't give any error. Can someone please explain?

CodePudding user response:

when I try to Initialize it as: ans = { {0,0,0,0},{1,1,1,1},{0,0,0,0},{1,1,1,1} };

Note that

ans = { {0,0,0,0},{1,1,1,1},{0,0,0,0},{1,1,1,1} };

is an assignment and not an initialization. On the other hand,

float a[4][4] = { {0,0,0,0},{1,1,1,1},{0,0,0,0},{1,1,1,1} };

is an initialization and so works.

The correct way to initialize ans would be:

Matrix4 ans{ {0,0,0,0},{1,1,1,1},{0,0,0,0},{1,1,1,1} };

Also note that array assignment is not possible in C .

There is also the concept of type decay that you have to take care(into account) for ans = a;. In particular, both ans and a are actually pointers and so when you write

ans = a;

you're actually assigning one pointer to another instead of one array to another.

You can use a std::vector as follows:

typedef std::vector<std::vector<float>> Matrix4;
void getXRotationMatrix(float theta, Matrix4 ans) {

    ans = { {0,0,0,0},{1,1,1,1},{0,0,0,0},{1,1,1,1} };

}

CodePudding user response:

Error with initialization of 2d arrays in C

when I try to Initialize it as:

ans = { {0,0,0,0},{1,1,1,1},{0,0,0,0},{1,1,1,1} };

Problem 1: That's not initialisation. That's assignment. Arrays cannot be assigned, but that's irrelevant due to next point.

Problem 2: ans is not an array. Function parameters are never arrays. Although you wrote it as an array, it has been adjusted to be a pointer to the element of the said array type. And the braced-init list that you provided is not a valid right hand argument for assigning a pointer.

however, it works when I initialize it as:

ans = a;

It becomes well-formed because a is a valid expression to assign to the pointer. The array will implicitly convert to a pointer to first element.

But the pointer is local to the function, so that function has no side-effects whatsoever.


I recommend returning instead of attempting to modify the parameter. Now, arrays cannot be returned in C , but there is a simple solution: You can return class instances, and classes may contain array as a member. There is a class template for such array wrapper in the standard library. It's called std::array. Example:

std::array<float[4], 4>
getXRotationMatrix() {
    return {{
         {0,0,0,0},
         {1,1,1,1},
         {0,0,0,0},
         {1,1,1,1},
    }};
}
  • Related