简体   繁体   中英

Passing an array pointer to a function and then reallocating the array and changing its values in C

I have a pretty basic question, I tried to answer it for many hours now but it still doesn't work. I want to malloc an array in main, pass it to another function, reallocate it and then change it's values. Why does the following code work:

void fun(int **array, int *size) {
    *array = (int *) realloc(*array, *size * sizeof(int));
    *array[0] = 1;
  
    return;
}

int main() {
    int size = 5;
    int *array = (int *) malloc(2 * sizeof(int));
    fun(&array, &size);
  
    return 0;
}

... but as soon as I try to change array[1] like this:

void fun(int **array, int *size) {
    *array = (int *) realloc(*array, *size * sizeof(int));
    *array[0] = 1;
    *array[1] = 2;

    return;
}

int main() {
    int size = 5;
    int *array = (int *) malloc(2 * sizeof(int));
    fun(&array, &size);
  
    return 0;
}

... it doesn't work anymore. It gives me segmentation fault and invalid write of size 4 .

In *array[0] = 1; , the [] operator has highest precedence, meaning it's interpreted as first doing pointer arithmetic on a int** , then de-reference it. It's equivalent to **(array + 0) = 1 which is not what you want.

For a single-dimension array you can simply do this:

#include <stdlib.h>

void fun (int** array, int size)
{
  int* tmp = realloc( *array, sizeof(int[size]) );
  if(tmp == NULL)
  {
    // error handling here
  }
  *array = tmp;

  (*array)[0]=1;
  (*array)[1]=2;
}

int main (void)
{
  int* array = malloc(2*sizeof *array);
  int size = 5;
  fun(&array, size);

  free(array);
  return 0;
}

For multiple dimensions, check out Correctly allocating multi-dimensional arrays

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