为什么我无法存储函数的 return 值?

Why am I unable to store the return value of the function?

我正在尝试 return 来自另一个函数的字符串值并将其存储为变量。这是我写的,但我无法解决这个问题。

#include "stdio.h"

void main() 
{
    printf("Hello World\n");
    char result[60];
    result = menuFunction();
}

const char* menuFunction() 
{
    return "Hello Again";
}

在你的代码中,result是数组类型,不是可修改的左值,因此不能用作赋值运算符的LHS。

引用 C11,章节 §6.5.16

An assignment operator shall have a modifiable lvalue as its left operand.

和第 6.3.2.1 章,(强调我的

An lvalue is an expression (with an object type other than void) that potentially designates an object; 64) if an lvalue does not designate an object when it is evaluated, the behavior is undefined. When an object is said to have a particular type, the type is specified by the lvalue used to designate the object. A modifiable lvalue is an lvalue that does not have array type, does not have an incomplete type, does not have a const-qualified type, and if it is a structure or union, does not have any member (including, recursively, any member or element of all contained aggregates or unions) with a const-qualified type.

解决方法:result定义为指针。

也就是说,

  • 对于托管环境,void main() 几乎是不允许的。您应该使用 int main(void) 以符合标准。
  • 在函数定义之前使用函数(调用)或 forward declaration 也是不允许的。您需要预先定义该函数或在使用它之前对其进行前向声明。