Initializing a pointer in a separate function in C

烈酒焚心 提交于 2019-11-25 23:26:37

问题


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


回答1:


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;
}



回答2:


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


来源:https://stackoverflow.com/questions/2486235/initializing-a-pointer-in-a-separate-function-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!