EDIT: (SOLVED) I've rewritten comments that solved the problem:
- "Pointers are not arrays. In case you actually had an array, which you don't, you can only initialize arrays during declaration, not assign to them in run-time".
- "This is invalid C. You need A.data[0] = 1; A.data[1] = 42; etc."
and, of course, there's the accepted answer too.
(disclaimer: just ignore mat_constr function because it's not related to this question (it's mat_constructor of another question I've posted, because I'm trying to edit the mat_transpose function on my own); mat_constr creates the matrix by taking the address of the matrix variable, rows, and cols).
void mat_constr(struct matrix* m, size_t rows, size_t cols) {
m->rows = rows; m->cols = cols;
m->data = calloc(rows * cols, sizeof(double));
}
// and, of course, mat_destroy to free the allocated memory.
void mat_destroy(struct matrix* m) {
free(m->data);
}
this is a very simple exercise, yet I can't figure out how to define an array (correctly).
I have a
struct matrix {
size_t rows;
size_t cols;
double* data
};
in the main function, I have to define a variable of type "struct matrix", and then I have to define the array. As follows:
int main(void) {
struct matrix A;
mat_constr(&A, 4, 4);
A.data = { /* a number */, /* another number* /, /* etc. */ };
}
the problem is that the compiler highlighted the first "{". in the array definition, and it says: "expected an expression". this is strange, because this is the definition style of the array, am I wrong?
CodePudding user response:
Assuming that mat_constr
allocates memory as a single array of double
, and makes the data
member point to it, then you can copy to this array.
For example using memcpy
and compound literals:
memcpy(A.data, (double[16]){ 1, 2, 3, ... }, 16 * sizeof(double));
[I made an assumption that mat_constr
allocates a single array of 4 * 4
elements in my example above. Please don't let us make assumptions, create a proper Minimal, Reproducible Example instead.]
You can of course copy a value to each element of the array individually instead:
A.data[0] = 1;
A.data[1] = 2;
A.data[2] = 3;
...
And if you want to set all elements to a single value you can of course use a loop:
for (unsigned i = 0; i < 16; i)
{
A.data[i] = 5;
}
Or if you want to set all elements to zero then either allocate with calloc
:
A->data = calloc(A->rows * A->cols, sizeof(double));
Or use memset
:
memset(A.data, 0, 16 * sizeof(double));
CodePudding user response:
The problem is that C has no notion of array litteral. And the equal sign can be used for 2 very different operations, assignment and initialization.
The brace enclosed expression can be used to initialize an array, but cannot be used to initialize a pointer nor can it be assigned to a pointer:
double data[] = {1., 2., 3.}; // array initialization: valid
double *data = {1., 2., 3.}; // INVALID attempt to initialize a pointer
double *d2;
d2 = {1., 2., 3.}; // INVALID assignment to a pointer