gpt4 book ai didi

c++ - 试图了解指针返回类型的工作原理

转载 作者:可可西里 更新时间:2023-11-01 15:52:44 25 4
gpt4 key购买 nike

我试图了解在以下情况下返回指针的工作原理:

#include <iostream>
using namespace std;

// Why does this work? I can even pass the return value to another function
// and the contents do not change.
char* StringFromFunction()
{
char* pReturn = "This string was created in the function.";
return pReturn;
}

// I know this is wrong because the memory address where 5 is stored can be
// overwritten.
int* IntegerFromFunction()
{
int returnValue = 5;
return &returnValue;
}

int main()
{
int* pInteger;
char* pString;

pString = StringFromFunction();
pInteger = IntegerFromFunction();

cout << *pInteger << endl << pString << endl;

return 0;
}

程序输出如我所料:

5
This string was created in the function.

我在 Visual C++ 2010 Express 中收到的唯一编译器警告是“c:\vc2010projects\test\main.cpp(14): warning C4172: returning address of local variable or temporary”并且它仅在我使用 IntegerFromFunction() 而不是 StringFromFunction() 时显示。

我认为我从上面的例子中理解的是:

StringFromFunction() 中,文本“This string was created in the function”的内存分配。发生在执行时,因为它是一个字符串文字,即使在函数返回后内容仍然存在于内存中,这就是为什么 main() 中的指针 pString 可以是传递给另一个函数,字符串可以在其中显示。

但是,对于 IntegerFromFunction(),当函数返回时,分配的内存现在已释放,因此可以覆盖该内存地址。

我想我的主要问题是,指向字符串文字的指针能否在整个程序中安全传递?

最佳答案

字符串文字实际上并不像自动变量那样存储在函数的堆栈中,而是存储在一个特殊的位置(如全局变量)。

请注意,写入它们不可移植,因此最好将它们用作 const char * 而不是 char *

关于c++ - 试图了解指针返回类型的工作原理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8685051/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com