Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing a pointer in a separate function in C

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)?

like image 421
pechenie Avatar asked Mar 21 '10 06:03

pechenie


People also ask

How do you initialize a pointer inside a function?

You need to initialize a pointer by assigning it a valid address. This is normally done via the address-of operator (&). The address-of operator (&) operates on a variable, and returns the address of the variable. For example, if number is an int variable, &number returns the address of the variable number.

Can we assign a pointer to a function in C?

In C, like normal data pointers (int *, char *, etc), we can have pointers to functions. Following is a simple example that shows declaration and function call using function pointer.


2 Answers

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;
}
like image 165
Michael Anderson Avatar answered Oct 16 '22 03:10

Michael Anderson


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);
like image 8
kennytm Avatar answered Oct 16 '22 03:10

kennytm