understand passing parameters by reference with dynamic allocation

前端 未结 5 2013
难免孤独
难免孤独 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:50

    You want to modify the value of n in main, not what n points to, so you need to pass a pointer to it. Since the type of n in main is int *, the parameter to alocar needs to be of type int **:

    void alocar(int **n)
    {
      *n = malloc(sizeof **n); // note no cast, operand of sizeof
      if (!*n)
        exit(-1);
    
      **n = 12;
      printf("%d\n", **n);
    }
    
    int main(void)
    {
      int *n;
      alocar(&n);
      printf("%d\n", *n);  // we've already tested against n being NULL in alocar
      free(n);             // always clean up after yourself
      return 0;
    }
    

提交回复
热议问题