使用int*&通过引用传递指针导致奇怪的问题

mot*_*iur 0 c++ pointers

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

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;
}
Run Code Online (Sandbox Code Playgroud)

如果我取消注释a行,它返回y的地址,*y返回一些未知的整数值.我打破了一些C++规范.我在编写此代码时使用了链接.我正在使用g ++ 7.3.0

And*_* DM 5

void passPointers(int* &a){
    int p = 5;
    a = &p;
} // p dies here
Run Code Online (Sandbox Code Playgroud)

指针变为悬空,因为您将其绑定到局部变量的地址.