这个问题在这里已有答案:
如何使用指针从不同的函数访问局部变量? 9个答案我有这个功能:
char* return_string(){ char buffer[] = "Hi world!"; return buffer; } bool test08() { char compare[] = "Hi world!"; int result = strcmp(compare,return_string()); if (result == 0) return true; return false; } int main() { if(test08) printf("\nTRUE"); else printf("\nFALSE"); }为什么这段代码在c ++ Shell中运行,而不是在代码块v.13.12(分段错误)中运行; 如果我将char buffer[]=声明更改为char *buffer=; 我是C ++的初学者(很容易知道)所以请明确......
This question already has an answer here:
How to access a local variable from a different function using pointers? 9 answersI have this function:
char* return_string(){ char buffer[] = "Hi world!"; return buffer; } bool test08() { char compare[] = "Hi world!"; int result = strcmp(compare,return_string()); if (result == 0) return true; return false; } int main() { if(test08) printf("\nTRUE"); else printf("\nFALSE"); }Why this code run in c++ Shell and it doesn't in codeblocks v. 13.12 (Segmentation fault); it'll work if i change my char buffer[]= declaration to char *buffer=; i'm a beginner at C++ (easy to know) so please be clear...
最满意答案
只需按以下方式更改函数return_string
const char* return_string(){ const char *buffer = "Hi world!"; return buffer; }原始函数实现的问题在于,数组buffer是函数的本地数组,其自动存储持续时间在退出函数后不会处于活动状态。
在修改后的函数中,使用了具有静态存储持续时间的字符串文字。 因此,您可以返回指向字符串文字的第一个字符的指针。
函数test08可以写得更简单
bool test08() { char compare[] = "Hi world!"; return strcmp( compare, return_string() ) == 0; }Just change the function return_string the following way
const char* return_string(){ const char *buffer = "Hi world!"; return buffer; }The problem with the original function implementation is that the array buffer is a local array of the function with the automatic storage duration that will not be alive after exiting the function.
In the modified function there is used a string literal that has static storage duration. So you may return a pointer to the first character of the string literal.
The function test08 can be written simpler
bool test08() { char compare[] = "Hi world!"; return strcmp( compare, return_string() ) == 0; }更多推荐
发布评论