I have this matrix that holds a 4x4 array of double:
typedef struct {
double data[4][4];
} mat;
And here I declare my mat
mat m1;
And i want to initialize my mat with zeros:
double data[4][4] = { { 0,0,0,0 },{ 0,0,0,0 },{ 0,0,0,0 },{ 0,0,0,0 } };
MAT_A.data = data;
And got this error:
expression must be a modifiable lvalue
And:
'=': left operand must be l-value
I also tried this:
MAT_A->data = data;
EDIT:
Another question is how to initiate mat ?
-
You'll better improve your question to give an actual minimal reproducible exampleBasile Starynkevitch– Basile Starynkevitch2017年12月21日 13:46:30 +00:00Commented Dec 21, 2017 at 13:46
4 Answers 4
The problem is that you cannot assign an array to a struct, nor an array to an array. The C syntax does not allow it.
And if you want to initialize a variable, you should not use assignment. These are different things; MAT_A.data = data; is assignment. This is initialization:
mat m =
{
.data = { { 0,0,0,0 },{ 0,0,0,0 },{ 0,0,0,0 },{ 0,0,0,0 } }
};
As for assignment, what you can do is assign a struct to a struct, for example by using a compound literal:
m = (mat)
{
.data = { { 0,0,0,0 },{ 0,0,0,0 },{ 0,0,0,0 },{ 0,0,0,0 } }
};
Comments
The problem is not in your initialization of the array data, but in the following assignment:
MAT_A.data = data;
In order to copy an array you need to copy the elements of the array individually:
for (int i = 0; i < 4; i++)
for (int j = 0; j < 4; j++)
MAT_A.data[i][j] = data[i][j];
Comments
i want to initiate my mat with zeros:
Then you could simply code:
mat m1 = {0};
or
double data[4][4] = {0};
(and {} instead of {0} would also practically work, even if non-standard)
and you could even use memset to clear the zone (with <string.h> standard header):
double data[4][4];
memset (&data, 0, sizeof(data));
or
memset (&m1, 0, sizeof(m1));
BTW, optimizing compilers like GCC (invoked as gcc -O2 -march=native) are likely to generate in practice the same machine code in all cases, if m1 or data is an automatic variable (on your call stack).
However, assignments of arrays (m1.data = data;) is illegal (because arrays decay into pointers).
And your title is wrong: C has no multi-dimensional arrays, only (mono-dimensional) arrays (perhaps arrays of arrays, arrays of structures, etc...).
3 Comments
{0} since {} would be invalid C.You could explicitly initialize the array as follows.
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
MAT_A.data[i][j] = 0;
}
}