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

Time:10-22

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.

CodePudding user response:

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

  • Related