I have recently come across the concept of dynamically allocated arrays and in applying it I encountered the following problem.
In a struct I defined some pointers to be allocated later:
typedef struct CELL {
int total;
int* number;
char** type;
}CELL;
In a function this struct has its memory allocated by malloc(), then the two pointers are allocated an 1D and 2D arrays via following methods:
int iallocate1D(int** arr, int m){
if ( (*arr = malloc(m*sizeof*arr))==NULL ) return 1;
return 0;
}
and
int callocate2D(char*** arr, int m, int n){
int i;
*arr = malloc(m*sizeof*arr);
if (*arr==NULL) return 1;
for(i=0;i<m;i++){
(*arr)[i] = malloc(n*sizeof(*arr)[i]);
if ((*arr)[i]==NULL) return 2;
}
return 0;
}
In the function that takes CELL* as argument, I initialized all arrays:
int loadCell(CELL** cell){
*cell = malloc(sizeof*cell);
iallocate1D(&(*cell)->number, 2); // 1D array of length 2
callocate2D(&(*cell)->type, 2, 3); // 2D array of size 2*3
}
Up to here everything is fine, and I scaned in some values to fill every element of the two arrays. I tested with printf, they seemed ok. And here came the problem, when I modified the value of
(*cell)->total = 1;
which I thought was not relevant, the 2D char array was also modified. Before this modification char[1][0] == 'L', but after this char[1][0] == '\3'. I printed every element and found that only this element was modified. Weired enough but I could not figure out where it went wrong, as that line was the only thing between the two prints of all array elements. I suspected that my dynamical allocation was wrong, but then I should not have been able to scan some values into the arrays in the first place.
Any hints will be appreciated. Thanks in advance.