Question

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.

Was it helpful?

Solution

*arr = malloc(m*sizeof*arr)

This allocates m objects of the size of *arr, but you want **arr. Some other allocations are similarly missing a level of indirection. They should be:

In iallocate1D:

*arr = malloc(m * sizeof **arr)

In callocate2D:

*arr = malloc(m * sizeof **arr);

(*arr)[i] = malloc(n * sizeof *(*arr)[i]);

In loadCell:

*cell = malloc(sizeof **cell);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top