c - 返回指向 C 中临时对象的指针

标签 c pointers return temporary

<分区>

Possible Duplicate:
returning a pointer to a literal (or constant) character array (string)?

下面的代码是否正确?

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));

让我担心的是该函数返回一个指向临时对象的指针。这种返回值的生命周期是多少?语言为 C89。

最佳答案

代码很好。您将返回一个指向字符串文字的指针,该文字在您的程序运行期间有效。

来自 C89 标准:

3.1.4 String literals

A character string literal has static storage duration and type ``array of char ,'' and is initialized with the given characters.

关于c - 返回指向 C 中临时对象的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14581344/

相关文章:

c - 如何在单独的线程中更新 GTK+ GUI 的一部分,该线程不断从另一个进程读取数据?

c++ - 指向 char 数组的指针的索引

c - 打印日历月

c - Execvp 不执行参数

C: 我怎样才能改变变量写入的寄存器?

java - 我怎样才能让我的 PrimeNumber 生成器工作?

bash - 源 shell 脚本的退出代码

javascript - 为什么 foo2() 在这里返回 undefined ?

c - 不使用 math.h 库的 Sin 函数

c++ - 如何创建指向结构的指针数组? C++