Far*_*uti 7 c arrays gcc c89 lvalue
在阅读了关于K&R书中结构的章节后,我决定做一些测试来更好地理解它们,所以我写了这段代码:
#include <stdio.h>
#include <string.h>
struct test func(char *c);
struct test
{
int i ;
int j ;
char x[20];
};
main(void)
{
char c[20];
struct {int i ; int j ; char x[20];} a = {5 , 7 , "someString"} , b;
c = func("Another string").x;
printf("%s\n" , c);
}
struct test func(char *c)
{
struct test temp;
strcpy(temp.x , c);
return temp;
}
Run Code Online (Sandbox Code Playgroud)
我的问题是:为什么c = func("Another string").x;工作(我知道这是非法的,但为什么它有效)?起初我用它写了strcpy()(因为这似乎是最合乎逻辑的事情)但我一直有这个错误:
structest.c: In function ‘main’:
structest.c:16:2: error: invalid use of non-lvalue array
Run Code Online (Sandbox Code Playgroud)
char c[20];
...
c = func("Another string").x;
Run Code Online (Sandbox Code Playgroud)
这不是有效的C代码.不是C89,不是C99,不是C11.
显然它在模式下编译最新gcc版本而没有诊断分配(发出诊断).这是在C89模式下使用时的错误.4.8-std=c89clanggcc
C90标准的相关报价:
6.2.2.1"可修改的左值是一个左值,它没有数组类型,没有不完整的类型,没有const限定类型.如果是结构或联合.没有任何成员(包括.递归地,所有包含结构或联合的任何成员)具有const限定类型."
和
6.3.16"赋值运算符的左操作数应具有可修改的左值."
6.3.16是一个约束,并且至少强制gcc要求发出没有的诊断gcc,因此这是一个错误.