简体   繁体   English

返回一个指向文字(或常量)字符数组(字符串)的指针?

[英]returning a pointer to a literal (or constant) character array (string)?

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. ...因为szLocal可以在函数返回后的某个时候被销毁。

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 . 另请参阅c / c ++何时分配字符串文字的答案。

It's ok in terms of allocation: the string literal is implicitly static . 在分配方面没问题:字符串文字是隐式static It's not ok to return a non- const pointer to a literal. 将非const指针返回到文字是不正确的。

If you want to return a modifiable (non- const ) string, declare it a static char[] . 如果你想返回一个可修改(非const )字符串,它声明一个static char[] Or better, return a copy: 或者更好,返回一份副本:

return strdup("something else");

Don't forget to free afterwards. 不要忘记随后free strdup is non-ISO but available almost everywhere (except MSVC, I believe). strdup是非ISO,但几乎可以在任何地方使用(我相信MSVC除外)。

The type of a string literal is const char * (see comments below) static char[] , but immutable. 字符串文字的类型是 const char * (参见下面的注释) static char[] ,但是不可变。 A string literal represents a pointer to statically allocated memory. 字符串文字表示指向静态分配内存的指针 Therefore: 因此:

  1. It is perfectly fine, to return a such a pointer. 返回一个这样的指针是完全没问题的。

  2. Your function return type must should be compatible with const char* , ie, return type char * will give you at least a warning may give you trouble later on. 你的函数返回类型 必须 const char*兼容,即返回类型char * 会给你至少一个警告, 可能会在以后给你带来麻烦。

  3. If you function may return both a literal or malloc ed string you have to be very careful about memory management. 如果你的函数可以返回文字或malloc ed字符串,你必须非常小心内存管理。 free ing a string literal probably will segfault. free一个字符串文字可能会段错误。

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

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