一个合法的数组赋值。可能吗? [英] A legal array assignment. Is it possible?

查看:165
本文介绍了一个合法的数组赋值。可能吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

阅读中的K&放大器结构的章节后,R的书,我决定做一些测试,以更好地了解他们,所以我写了这片code的:

 的#include<&stdio.h中GT;
#包括LT&;&string.h中GT;结构测试FUNC(字符* C);结构测试
{
    INT I;
    诠释J;
    炭×〔20〕;
};主要(无效)
{
    焦C [20];
    结构{INT I;诠释J;炭×〔20];}一个= {5,7,someString},B;
    C = FUNC(另一个字符串)x。
    的printf(%S \\ n,C);
}结构测试FUNC(字符* C)
{
    结构试验温度;
    的strcpy(temp.x,C);
    返回温度;
}

我的问题是:为什么是 C = FUNC(另一个字符串)X; 工作(我知道这是非法的,但为什么它的工作)?起初,我写的使用的strcpy()(因为这似乎做的最顺理成章的事情),但我一直有这个错误:

  structest.c:在函数'主':
structest.c:16:2:错误:无效使用非左值数组


解决方案

 字符C [20];
    ...
    C = FUNC(另一个字符串)x。

这是不合法的C code。不要在C89,而不是在C99,而不是在C11。

显然,这与最新的 GCC 版本 4.8 -std = C89 <编译/ code>模式,而不诊断为赋值(发出诊断)。这是 gcc的一个bug 在C89模式下使用时。

从C90标准的相关报价:


  

6.2.2.1修改的左值是不具有数组类型的左值,没有一个不完整的类型,不具有常量限定类型。如果它是一个结构或联合。没有任何成员(包括。递归,所有的任何成员包含结构或联合)用const限定型。



  

6.3.16赋值操作员有修改的左值作为其左操作数。


6.3.16是一种约束,并规定至少 GCC 来发出诊断其 GCC 不,所以这是一个错误。

After reading the chapter about structures in the K&R book I decided to make some tests to understand them better, so I wrote this piece of code:

#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;    
}

My question is: why is c = func("Another string").x; working (I know that it's illegal, but why is it working)? At first I wrote it using strcpy() (because that seemed the most logical thing to do) but I kept having this error:

structest.c: In function ‘main’:
structest.c:16:2: error: invalid use of non-lvalue array

解决方案

    char c[20];
    ...
    c = func("Another string").x;

This is not valid C code. Not in C89, not in C99, not in C11.

Apparently it compiles with the latest gcc versions 4.8 in -std=c89 mode without diagnostic for the assignment (clang issues the diagnostic). This is a bug in gcc when used in C89 mode.

Relevant quotes from the C90 Standard:

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."

and

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

6.3.16 is a constraint and imposes at least for gcc to issue a diagnostic which gcc does not, so this is a bug.

这篇关于一个合法的数组赋值。可能吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆