简体   繁体   中英

Reallocating memory for a two dimensional array in C

My goal is to dynamically reallocate memory for a two dimensional int array in C. I know there are already several questions about that topic, but unfortunately my code does not run properly and i don't know what is going wrong.

First i am allocating memory:

int n = 10;
int m = 4;
int** twoDimArray;
twoDimArray = (int**)malloc(n * sizeof(int*));
for(int i = 0; i < n; i++) {
   twoDimArray[i] = (int*)malloc(m * sizeof(int));
}

And initializing the array with integer numbers:

for(int i = 0; i < n; i++) {
   for(j = 0; j < 4; j++) {
      twoDimArray[i][j] = i * j;
   }
}

Then i use realloc() to reallocate memory dynamically:

int plus = 10;
int newArraySize = n + plus;
twoDimArray = (int**)realloc(twoDimArray, newArraySize * sizeof(int));

I am expecting my aray twoDimArray to be accessible at [10][0] now, but when running

printf("twoDimArray[10][0] = %d\n", twoDimArray[10][0]);

i get an "EXC_BAD_ACCESS" runtime error.

Probably i am missing something rather simple, but since i am new to C and can't figure out my mistake. Any help is appreciated.

reallocating the array of pointers is necessary, but then you have only n values that point to something valid. You need to allocate the rest of the sub-arrays because the newly allocated memory points to unallocated/invalid areas. The error is not from accessing the pointer, but from dereferencing it.

You need to add something like:

for(int i = n; i < n+plus; i++) {
   twoDimArray[i] = malloc(m * sizeof(int));
}

(same goes for deallocation: first deallocate the arrays in a loop, then deallocate the array of pointers)

Aside:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM