在c ++函数中返回char *时出错[重复](Error returning char* in c++ function [duplicate])

编程入门 行业动态 更新时间:2024-10-25 06:25:48
在c ++函数中返回char *时出错[重复](Error returning char* in c++ function [duplicate])

这个问题在这里已有答案:

如何使用指针从不同的函数访问局部变量? 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 answers

I 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; }

更多推荐

本文发布于:2023-07-27 15:30:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1292416.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   char   Error   duplicate   function

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!