Vit*_*y P 3 c pointers return temporary
可能重复:
返回指向文字(或常量)字符数组(字符串)的指针?
以下代码是否正确?
const char* state2Str(enum State state)
{
switch (state)
{
case stateStopped: return "START";
case stateRunning: return "RUNNING";
default: return "UNKNOWN";
}
}
printf("State is: %s\n", state2Str(stateRunning));
Run Code Online (Sandbox Code Playgroud)
令我担心的是该函数返回一个指向临时对象的指针.这种返回值的生命周期是多少?语言是C89.
代码很好.您将返回一个指向字符串文字的指针,该字符串文字在程序的持续时间内有效.
从C89标准:
3.1.4字符串文字
字符串文字具有静态存储持续时间和类型``char of char''',并使用给定的字符进行初始化.