understand passing parameters by reference with dynamic allocation

前端 未结 5 2017
难免孤独
难免孤独 2021-01-25 16:59

I\'m trying understand how to pass a parameter by reference in C language. So I wrote this code to test the behavior of parameters passing:

#include 

        
5条回答
  •  无人共我
    2021-01-25 17:58

    C is pass-by-value, it doesn't provide pass-by-reference. In your case, the pointer (not what it points to) is copied to the function paramer (the pointer is passed by value - the value of a pointer is an address)

    void alocar(int* n){
       //n is just a local variable here.
       n = (int*) malloc( sizeof(int));
      //assigning to n just assigns to the local
      //n variable, the caller is not affected.
    

    You'd want something like:

    int *alocar(void){
       int *n = malloc( sizeof(int));
       if( n == NULL )
          exit(-1);
       *n = 12;
       printf("%d.\n", *n);
       return n;
    }
    int main()
    {
       int* n;
       n = alocar();
       printf("%d.\n", *n);
       return 0;
    }
    

    Or:

    void alocar(int** n){
       *n =  malloc( sizeof(int));
       if( *n == NULL )
          exit(-1);
       **n = 12;
       printf("%d.\n", **n);
    }
    int main()
    {
       int* n;
       alocar( &n );
       printf("%d.\n", *n);
       return 0;
    }
    

提交回复
热议问题