按引用传递但参数值为空

pass by reference but the value of parameter is null

我正在用 C 编程。

我有一个结构:

 struct MY_TYPE {
      boolean flag;
      short int value;
      double stuff;
    };

我有一个函数,它将指向 MY_TYPE 的指针作为参数:

getData(struct MY_TYPE ** m_type) {
  // I initialise an object of MY_TYPE
  struct MY_TYPE a = {.value = 123};
  // I assign the address of above object to a pointer of MY_TYPE
  struct MY_TYPE *p = &a;
  // I assign the address of above pointer to parameter
  m_type = &p;
}

在我的主程序中,我调用了上面的函数:

struct MY_TYPE *my_param;
getData(&my_param);

// I set a break pointer here, and it shows me my_param is NULL, why?

我调用getData(...)后,传入的参数是NULL,为什么?

您正在使用一个局部变量,这个变量的生命周期以函数结束,使用malloc以保留他的值。

struct MY_TYPE *p = malloc(sizeof *p);

if (p != NULL) {
    p->value = 123;
    *m_type = p; /* Dereference the passed pointer to pointer */
}

这是一个未定义的行为,它不会发生,因为您正在分配一个按值传递的指针。

  • 调用者会忽略您在 getData 中对 m_type 所做的任何更改。您需要分配 *m_type 才能使更改有所不同。
  • 进行此更改后,您将开始出现未定义的行为,因为 struct a 一旦 getData returns.
  • 就超出范围

您可以通过返回在您的函数中初始化的动态分配块来解决此问题:

getData(struct MY_TYPE ** m_type) {
  // I initialize an object of MY_TYPE
  struct MY_TYPE a = {.value = 123};
  // I make a copy into dynamic memory
  struct MY_TYPE *copy = malloc(sizeof(struct MY_TYPE));
  memcpy(copy, &a);
  // I assign the address of above pointer to parameter
  *m_type = copy;
}

调用方需要释放从调用中接收到的内存:

struct MY_TYPE *my_param;
getData(&my_param);
... // Use my_param here.
// Now that I am done with my_param...
free(my_param);