简体   繁体   English

C:函数返回指针

[英]C: function returning pointer

I have a difficulty in a conceptual problem 我在概念上有困难

consider this code: 考虑以下代码:

char *myfunc()
{
char *temp = "string";
return temp;
}

int main()
{
char* ptr = myfunc();
} 

I can't understand why ptr points to "string" after the function call. 我不明白为什么在函数调用后ptr指向“字符串”。 myfunc() creates an address in the stack which has the value "string" and another address which has the address of "string". myfunc()在堆栈中创建一个值为“ string”的地址,并为另一个地址为“ string”的地址。 When the function ends, the memory it had in the stack is freed so it should return a pointer pointing to an address that does not contain "string" anymore. 函数结束时,将释放其在堆栈中的内存,因此它应返回一个指针,该指针指向不再包含“字符串”的地址。

The location of the temp variable is on the stack, but the location of the string literal (to which temp points) is not stored on the stack. temp变量的位置在堆栈上,但是字符串文字( temp指向的位置)的位置未存储在堆栈上。 All string literals have a lifetime of the full runtime of the program, and so pointers to a string literal can be passed around freely. 所有字符串文字都有程序整个运行时的生命周期,因此可以自由传递指向字符串文字的指针。

But you should really get in the habit of using const char * when pointing to string literals, as string literals can't be modified. 但是,在指向字符串文字时,您应该真正养成使用const char *的习惯,因为无法修改字符串文字。


From ISO/IEC 9899:2011, §6.4.5/6: 根据ISO / IEC 9899:2011第6.4.5 / 6条:

The multibyte character sequence is then used to initialize an array of static storage duration 然后,将多字节字符序列用于初始化静态存储持续时间数组

(Emphasis mine) (强调我的)

When the specification says "static storage duration" it means that the lifetime is the same as the execution of the program. 当规范说“静态存储持续时间”时,表示生存期与程序的执行时间相同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM