16

I need to do a simple thing, which I used to do many times in Java, but I'm stuck in C (pure C, not C++). The situation looks like this:

int *a;

void initArray( int *arr )
{
    arr = malloc( sizeof( int )  * SIZE );
}

int main()
{
    initArray( a );
    // a is NULL here! what to do?!
    return 0;
}

I have some "initializing" function, which SHOULD assign a given pointer to some allocated data (doesn't matter). How should I give a pointer to a function in order to this pointer will be modified, and then can be used further in the code (after that function call returns)?

Bo Persson
  • 90,663
  • 31
  • 146
  • 203
pechenie
  • 1,908
  • 2
  • 18
  • 17

2 Answers2

27

You need to adjust the *a pointer, this means you need to pass a pointer to the *a. You do that like this:

int *a;

void initArray( int **arr )
{
    *arr = malloc( sizeof( int )  * SIZE );
}

int main()
{
    initArray( &a );
    return 0;
}
Michael Anderson
  • 70,661
  • 7
  • 134
  • 187
  • 3
    Alternatively (and better IMHO) `int *initArray(size_t s) { return malloc(sizeof(int) * s); }` and then use it as `int *arr = initArray(SIZE);` – Chris Lutz Mar 21 '10 at 06:43
  • 1
    Chris, I shouldn't, because this example is a kind of unnatural one. The "initArray" function in my real situation returns a value, so I can't use it. But thanx anyway :) – pechenie Mar 21 '10 at 06:47
8

You are assigning arr by-value inside initArray, so any change to the value of arr will be invisible to the outside world. You need to pass arr by pointer:

void initArray(int** arr) {
  // perform null-check, etc.
  *arr = malloc(SIZE*sizeof(int));
}
...
initArray(&a);
kennytm
  • 510,854
  • 105
  • 1,084
  • 1,005