Initializing a pointer in a separate function in C

后端 未结 2 1716
刺人心
刺人心 2020-11-22 10:42

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 initA         


        
相关标签:
2条回答
  • 2020-11-22 11:24

    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);
    
    0 讨论(0)
  • 2020-11-22 11:34

    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;
    }
    
    0 讨论(0)
提交回复
热议问题