【问题标题】:Passing pointers by reference using int*& is causing odd problems [duplicate]使用 int*& 通过引用传递指针会导致奇怪的问题 [重复]
【发布时间】:2019-06-08 14:14:22
【问题描述】:

我正在编写以下内容以通过引用传递指针。但是,当我尝试取消引用指针时,它会给出意外的值。

void passPointers(int* &a){
    int p = 5;
    a = &p;
}
int main(){
  int x = 3;
  int *y= &x;
  cout<<"y is "<<y<<" *y is "<<*y<<endl;
  passPointers(y);
      
  //cout<<"y is "<<y<<" *y is "<<*y<<endl;//line a
  cout<<" *y is "<<*y<<endl;//It returns 5
  return 0;
}

如果我取消注释行 a,它返回 y 的地址,*y 返回一些未知的整数值。我是否违反了 C++ 的一些规范。 我在编写这段代码时使用了this 链接。 我正在使用 g++ 7.3.0

【问题讨论】:

  • p 在执行离开passPointers() 后立即被销毁。因此指针变得悬空,读取指向的值会给你未定义的行为。
  • 您正在返回一个局部变量的地址。该变量在该函数之外不存在,访问它是未定义的行为。

标签: c++ pointers


【解决方案1】:
void passPointers(int* &a){
    int p = 5;
    a = &p;
} // p dies here

指针变得悬空,因为您将它绑定到局部变量的地址。

【讨论】:

    猜你喜欢
    • 2016-08-26
    • 2014-10-12
    • 2022-01-16
    • 2011-11-10
    • 1970-01-01
    • 1970-01-01
    • 2015-10-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多