Search code examples
carrayspointerscompound-literals

Function for allocating arrays in other function in C


I am having problems when using a function to allocate arrays in another function. Here is the segment that causes problems:

void
array_allocator(int method, int** a, int** b){
  if (method == 0)
  {
    (*a) = (int[5]) {0, 1, 2, 3, 4};
    (*b) = (int[5]) {5, 6, 7, 8, 9};

    printf ("in array_allocator\n");
    printf ("a = (%d, %d, %d, %d, %d)\n",(*a)[0],(*a)[1],(*a)[2],(*a)[3],(*a)[4]);
    printf ("b = (%d, %d, %d, %d, %d)\n",(*b)[0],(*b)[1],(*b)[2],(*b)[3],(*b)[4]);
  }
  else printf("unknown method\n");
}

void
some_function (int method){
  int *a, *b;

  array_allocator(method, &a, &b);

  printf ("in some_function\n");
  printf ("a = (%d, %d, %d, %d, %d)\n",a[0],a[1],a[2],a[3],a[4]);
  printf ("b = (%d, %d, %d, %d, %d)\n",b[0],b[1],b[2],b[3],b[4]);
}

int main()
{
  int method = 0;
  some_function(method);
  return 0;
}

After compiling with gcc and executing I get the output:

in array_allocator
a = (0, 1, 2, 3, 4)
b = (5, 6, 7, 8, 9)
in some_function
a = (10, 0, 4196346, 0, 1448083200)
b = (-730692608, 32637, 16, 0, 4196346)

Somehow, the values after the array allocation become random, and even change if I add some printf() function before printing the array values at some_function().


Solution

  • This doesn't work, as the values you assign only exist locally:

    (*a) = (int[5]) {0, 1, 2, 3, 4};
    (*b) = (int[5]) {5, 6, 7, 8, 9};
    

    You should instead do this:

    *a = malloc(sizeof(int)*5);
    *b = malloc(sizeof(int)*5);
    (*a)[0] = 0;
    (*a)[1] = 2;
    (*a)[2] = 2;
    (*a)[3] = 3;
    (*a)[4] = 4;
    (*b)[0] = 5;
    (*b)[1] = 6;
    (*b)[2] = 7;
    (*b)[3] = 8;
    (*b)[4] = 9;
    

    Also, don't forget to free(a) and free(b) at the end of some_function()