【问题标题】:pass by reference but the value of parameter is null通过引用传递但参数的值为空
【发布时间】:2016-09-19 10:09:52
【问题描述】:

我正在用 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,为什么?

【问题讨论】:

  • 你知道一些关于本地作用域的变量.....
  • 无论如何,变量 'a' 是 getData() 函数的本地变量,因此您不能返回它(或指向它的指针,或者更糟糕的是指向也是局部变量的指针的指针)。

标签: c function struct parameter-passing pass-by-reference


【解决方案1】:

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

  • 调用者会忽略您在getData 中对m_type 所做的任何更改。您需要分配 *m_type 以使更改产生任何影响。
  • 进行此更改后,您将开始出现未定义的行为,因为一旦getData 返回,struct a 就会超出范围。

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

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-10-07
      • 2017-07-11
      • 1970-01-01
      • 2011-08-21
      • 2017-09-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多