在阅读了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;
}
我的问题是:为什么 c = func("Another string").x;
有效(我知道这是非法的,但为什么有效)?起初我使用 strcpy()
编写它(因为这似乎是最合乎逻辑的事情)但我一直有这个错误:
structest.c: In function ‘main’:
structest.c:16:2: error: invalid use of non-lvalue array
最佳答案
char c[20];
...
c = func("Another string").x;
这不是有效的 C 代码。不在 C89 中,不在 C99 中,不在 C11 中。
显然,它在 -std=c89
模式下使用最新的 gcc
版本 4.8
编译,没有分配诊断(clang
发出诊断)。这是在 C89 模式下使用时 gcc
中的错误。
C90标准的相关引述:
6.2.2.1 "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 of all contained structures or unions) with a const-qualified type."
和
6.3.16 "An assignment operator shall have a modifiable lvalue as its left operand."
6.3.16 是一个约束,至少对 gcc
施加了一个诊断,而 gcc
没有,所以这是一个错误。
关于c - 合法的数组赋值。是否可以?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18412094/