c ++函数[duplicate]中返回地址与返回指针之间的区别

问题描述 投票:0回答:2

当传递a = 4时,给定的函数返回:

int* temp1(int a)
{
   int b = a*2;
   return &b;
}

int* temp2(int a)
{
   int b = a*2;
   int *p = &b;
   return p;
}

int main()
{
   cout << *temp1(4);  // error
   cout << *temp2(4);  // output = 8
}

为什么以上两个功能具有不同的行为?而以下具有相同的输出?

int a = 3;
cout << *(&a); // 3

int a= 3;
int *p = &a;
cout << *p; // 3
c++ pointers function-pointers
2个回答
0
投票

两个功能的行为是相同的。两者均返回指向局部变量的指针。函数返回时,指向对象的生存期都结束。因此,如果程序取消引用返回的指针之一,则该程序的行为是不确定的。

© www.soinside.com 2019 - 2024. All rights reserved.