C语言

结构体 共用体变量直接相互赋值

2020-08-03  本文已影响0人  sakura579
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
main()
{
    struct node 
    {
        int data;
        char ddd[10];   
    }; 
    struct node aaa= {1,"abcdef"};
    struct node bbb;
    bbb = aaa;
    printf("%s\n",aaa.ddd);
    aaa.data = 2;
    strcpy(aaa.ddd,"qwerdf");
    printf("%s\n",aaa.ddd);
    printf("%s\n",bbb.ddd);
    
}

结果
abcdef
qwerdf
abcdef

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
main()
{
    union node
    {
        int num;
        struct{
            int x,y,z;
        }u;
    }a,b;
    a.num = 10;
    a.u.x = 1;
    a.u.y = 2;
    a.u.z = 3;
    printf("%d\n",a.u.x);
    b = a;
    b.num = 0;
    printf("%d\n",a.u.x);   
    printf("%d\n",b.u.x);
    printf("%d\n",b.u.z);
}

结果
1
1
0
3

可见相互赋值 并不是指向同一个
否则更改值 都会受到影响

上一篇 下一篇

猜你喜欢

热点阅读