比如:
struct A{
char v1[20];
int v2;} a,b;
a = b;
这是没有任何问题的赋值.
struct B{
char *v1;
int v2;} c,d;
c = d;
这种结构体赋值,就需要注意(包括在C++里)。对于指针赋值,它不是数据进行了复制保存而是多了一个指针指向而已,这样一旦b对象释放,a的指向就成了非法的垃圾数据。
所以在 C/C++ 中,有些需要要另外自己定义复制函数的。
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.
#include <stdio.h>
typedef struct {
int domain;
int set_id;
int ctxt;
}Dcs;
int main(int argc, char **argv)
{
Dcs dcs = {10,20,30};
Dcs dcs1;
dcs1 = dcs;
printf("befor:dcs1 = %d %d %d \n",
dcs1.domain, dcs1.set_id, dcs1.ctxt);
dcs.domain = 20;
dcs.set_id = 20;
dcs.ctxt = 20;
printf("last dcs = %d %d %d \n",
dcs.domain, dcs.set_id, dcs.ctxt);
printf("last dcs1 = %d %d %d \n",
dcs1.domain, dcs1.set_id, dcs1.ctxt);
return 0;
}
转载:http://bbs.csdn.net/topics/300160344
















