I would like to create a struct that contains a bidimensional array in C, but I don't know how to initialize it because I don't know the dimensions. Is there a way to do it?
struct myStruct {
int m[][];
};
I would like to create a struct that contains a bidimensional array in C, but I don't know how to initialize it because I don't know the dimensions. Is there a way to do it?
struct myStruct {
int m[][];
};
If the outer most dimension is known at the compile time then you can declare the structure with a flexible array member like for example
#define N 10
//...
struct myStruct {
size_t m;
int a[][N];
};
Otherwise instead of the array you should use a pointer of the type int **
struct myStruct {
size_t m;
size_t n;
int **a;
};
where data members m
and n
are used to specify dimensions of the allocated dynamically arrays using the pointer a
.
In both cases arrays are allocated dynamically.
You can allocate it some amount of memory, for example 5 times 5 using malloc and then reallocate in case it's not enough.
E.g.:
int *m= (int *)malloc(rows * cols * sizeof(int));