72.结构体变量直接赋值

目录

一.结构体变量直接赋值

二.视频教程


一.结构体变量直接赋值

通过上节课的学习得出了一个结论:俩个相同类型的结构体变量直接可以只用赋值号进行赋值。

像这样:

struct test {
    int a;
    int b;
};



int main(void)
{
    struct test x = {1,2};
    struct test z;

    z = x;
    printf("z.a is %d,z.b is %d\n",z.a,z.b);


    return 0;
 
}

我们改一下这个例子,在test结构体中添加一个指针类型的成员。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct test {
    int a;
    int b;
    char *title;
};



int main(void)
{
    struct test x = {1,2};
    x.title = malloc(sizeof(char));
    strcpy(x.title,"a");
    struct test z;
    
    z = x;
    printf("z.a is %d,z.b is %d,z.title is %s\n",z.a,z.b,z.title);


    return 0;
 
}

运行结果:

通过实验,这个例子也可以运行成功,如果我们修改一下结构体变量x中的title成员,会发现结构体变量z中的title成员也会发生变化。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct test {
    int a;
    int b;
    char *title;
};



int main(void)
{
    struct test x = {1,2};
    x.title = malloc(sizeof(char));
    strcpy(x.title,"a");
    struct test z;

    z = x;
    strcpy(x.title,"b");
    printf("z.a is %d,z.b is %d,z.title is %s\n",z.a,z.b,z.title);


    return 0;
 
}

运行结果:

很显然,这是不正确的。

这是为什么呢,我们来看这张图

因为指针共同指向了一个相同的地址,所以该地址指向的值发生变化会都发生变化。所以需要补充的结论是:如果结构体中有指针成员,切勿直接赋值,要分开赋值,否则成员之间会互相影响。

所以正确的写法是:


#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct test {
    int a;
    int b;
    char *title;
};



int main(void)
{
    struct test x = {1,2};
    x.title = malloc(sizeof(char));
    strcpy(x.title,"a");

    struct test z  = {3,4};
    z.title = malloc(sizeof(char));
    strcpy(z.title,"b");

    printf("x.a is %d,x.b is %d,x.title is %s\n",x.a,x.b,x.title);
    printf("z.a is %d,z.b is %d,z.title is %s\n",z.a,z.b,z.title);



    return 0;
 
}

运行结果:

二.视频教程

72.结构体变量直接赋值_哔哩哔哩_bilibili

  • 6
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值