比如:
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