I am trying to create a struct. One of the elements of the struct is an array that should be able to grow if needed.
I do this:
int COLS=2, ROWS=20;
long int (*array)[COLS] = malloc(sizeof(int[ROWS][COLS]));
struct test{
long int (*arr)[COLS];
};
struct test *s_test = malloc(sizeof(s_test));
s_test->arr = array;
for (int i=0; i<ROWS; i++){
array[i][0]=i;
array[i][1]=i+20;
printf("0:%ld\t1:%ld\n",s_test->arr[i][0], s_test->arr[i][1]);
}
but the compiler says:
test.c:10:14: error: fields must have a constant size: 'variable length array in structure' extension will never be supported
long int (*arr)[COLS];
This works ok:
int COLS=2, ROWS=20;
long int (*array)[COLS] = malloc(sizeof(int[ROWS][COLS]));
long int (*arr)[COLS];
//struct test{
// long int (*arr)[COLS];
//};
struct test *s_test = malloc(sizeof(s_test));
//s_test->arr = array;
arr = array;
for (int i=0; i<ROWS; i++){
array[i][0]=i;
array[i][1]=i+20;
printf("0:%ld\t1:%ld\n", arr[i][0], arr[i][1]); //s_test->arr[i][0], s_test->arr[i][1]);
}
BTW, I, mistakenly forgot to delete the declaration of a struct test (which is not defined now) and the compiler didn't complain...). I will also appreciate a very simple (if possible) explanation of why.
1 - I clearly don't know how to solve this problem.
2 - Does the struct HAS to be a pointer?
3 - Can't the element arr be a pointer to theh 2darray?
Thank you a lot!