首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

C语言什么时候支持结构体变量之间直接赋值,该如何处理

2012-03-02 
C语言什么时候支持结构体变量之间直接赋值structA{inta1inta2}A1,A2.....A1A2?这种直接赋值什么时候可

C语言什么时候支持结构体变量之间直接赋值
struct   A
{
int   a1;
int   a2;
}A1,A2;

.....

A1=A2?

这种直接赋值什么时候可以的啊,我记得以前谭老师的书说这种是错误的

[解决办法]
谭浩强那本书最大的作用就是通过找其中的错误来检验自己的水平。

C语言直接支持结构体变量的赋值,它是按值逐元素赋值的。

参看K&R A.7.17 Assignment Expressions

In the simple assignment with =, the value of the expression replaces that of the object referred to by the lvalue. One of the following must be true: both operands have arithmetic type, in which case the right operand is converted to the type of the left by the assignment; or both operands are structures or unions of the same
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
type; or one operand is a pointer and the other is a pointer to void, or the left
~~~~
operand is a pointer and the right operand is a constant expression with value 0; or both operands are pointers to functions or objects whose types are the same except for the possible absence of const or volatile in the right operand.

进一步,C99标准§6.7.2.1上说:
struct s { int n; double d[]; };
……
struct s *s1;
struct s *s2;
……
The assignment:
*s1 = *s2;
only copies the member n and not any of the array elements.

而C99标准的TC2 Committee Draft则进一步指出:
if any of the array elements are within the first sizeof (struct s) bytes
of the structure, they might be copied or simply overwritten with indeterminate values.

热点排行