C中结构体是否能用=运算符直接赋值的问题

来源:互联网 发布:电容屏原理 知乎 编辑:程序博客网 时间:2024/06/05 02:33

印象中,C中的结构体是不能用等号运算符赋值的,以前写的程序对两个结构体内容交换的时候,都是单独建立一个swap函数来对两个结构体的各个成员逐一交换。

然而,查阅资料加实践后,发现=是可以用来给结构体赋值的。

首先来看一下文献:

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.
【http://bbs.csdn.net/topics/110160458】

实践的效果是

运行平台:win10 64位
visual Studio 2013

#include<stdio.h>  #include<string.h>char str1[10] = "Cantjie";char str2[10] = "Ganlv";struct emp{    int wage;    char sex;    char dept[20];    char name[20];    int num[2];    char *p;}a[10] = { 0, 'F', "FirstDept", "FirstName",0,0,str1, 1,'M',"SecondDept","SecondName",1,1 ,str2};int main(){    int i, size;    struct emp temp;    struct emp *p = &temp;    size = sizeof(struct emp);    printf("%d\n", size);    memcpy(p, &a[0], size);    memcpy(&a[0], &a[1], size);    memcpy(&a[1], p, size);    printf("%d,%c,%s,%s,%d,%d,%s\n", a[0].wage, a[0].sex, a[0].dept, a[0].name, a[0].num[0], a[0].num[1], a[0].p);    printf("%d,%c,%s,%s,%d,%d,%s\n", a[1].wage, a[1].sex, a[1].dept, a[1].name, a[1].num[0], a[1].num[1], a[1].p);    temp = a[0];    a[0] = a[1];    a[1] = temp;    printf("%d,%c,%s,%s,%d,%d,%s\n", a[0].wage, a[0].sex, a[0].dept, a[0].name, a[0].num[0], a[0].num[1], a[0].p);    printf("%d,%c,%s,%s,%d,%d,%s\n", a[1].wage, a[1].sex, a[1].dept, a[1].name, a[1].num[0], a[1].num[1], a[1].p);}

运行结果:
60
1,M,SecondDept,SecondName,1,1,Ganlv
0,F,FirstDept,FirstName,0,0,Cantjie
0,F,FirstDept,FirstName,0,0,Cantjie
1,M,SecondDept,SecondName,1,1,Ganlv

在这个程序中,memcpy与=的效果相同。

值得注意的是,这种赋值方式是“浅赋值”,当结构体中含有指针时,并不会使temp中的char *p另外开辟一个空间用于存储字符串。

相关文章:http://blog.csdn.net/hazir/article/details/9429017

原创粉丝点击