返回指针到文本(或常量)字符数组(字符串)? [英] returning a pointer to a literal (or constant) character array (string)?

查看:99
本文介绍了返回指针到文本(或常量)字符数组(字符串)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这是错误的:

 的char * getSomething(){
    炭szLocal [5];
    / *装上去的char数组中不知何故* /
    返回szLocal;
}

...因为szLocal可以在函数返回之后的某个时候销毁。

但是,这行吗?

 的char * getSomethingElse(){
    返回别的东西;
}


解决方案

这实际上是确定。文字字符串通常是在分配的剩余可用只要你的程序正在运行一个不变的内存区域。

又见答案<一个href=\"http://stackoverflow.com/questions/1971183/when-does-c-allocate-deallocate-string-literals\">when没有C / C ++分配字符串的。

I know this is wrong:

char* getSomething() {  
    char szLocal[5];  
    /* put something in the char array somehow */  
    return szLocal;  
}  

...because szLocal can be destroyed sometime after the function returns.

But is this ok?

char* getSomethingElse() {  
    return "something else";  
}  

解决方案

That is actually OK. The string literal is usually allocated in an immutable memory area that remains available for as long as your program is running.

See also the answers to when does c/c++ allocate string literals.

这篇关于返回指针到文本(或常量)字符数组(字符串)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆