结构体指针的一个赋值操作

# cat test.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct _tag_tst_ {
    int a;
    char b;
} tst_t;

typedef struct _tag_buf_ {
    int len;
    char *ptr;
    char ch;
} buf_t;

void
func_2(void)
{
    buf_t *buf1 = NULL;
    buf_t *buf2 = NULL;
    int len = 10;

    buf1 = (buf_t *)malloc(sizeof(buf_t));
    if (NULL == buf1) {
        printf("Error: malloc failed\n");
        return;
    }

    buf1->len = len;
    buf1->ptr = (char *)malloc(sizeof(char) * len);
    if (NULL == buf1->ptr) {
        printf("Error: malloc failed\n");
        return;
    }
    strncpy(buf1->ptr, "Hello", buf1->len);
    buf1->ch = 120;

    printf("buf1 ptr: %s, len: %d, ch: %d\n", buf1->ptr, buf1->len, buf1->ch);

    buf2 = (buf_t *)malloc(sizeof(buf_t));
    if (NULL == buf2) {
        printf("Error: malloc failed\n");
        return;
    }
    buf2->len = len;
    buf2->ptr = (char *)malloc(sizeof(char) * len);
    if (NULL == buf2->ptr) {
        printf("Error: malloc failed\n");
        return;
    }

    *buf2 = *buf1;   //????????

    free(buf1->ptr);
    buf1->ptr = NULL;
    free(buf1);
    buf1 = NULL;

    printf("buf2 ptr: %s, len: %d, ch: %d\n", buf2->ptr, buf2->len, buf2->ch);

    free(buf2->ptr);
    free(buf2);
}

void
func_1(void)
{
    tst_t *t1 = NULL;
    tst_t *t2 = NULL;

    t1 = (tst_t *)malloc(sizeof(tst_t));
    if (NULL == t1) {
        printf("Error: malloc failed\n");
        return ;
    }

    t1->a = 65530;
    printf("*t1: %x, t1: %x, &t1: %x\n", *t1, t1, &t1);
    t1->b = 120;
    printf("t1->a: %d, t1->b: %d\n", t1->a, t1->b);

    t2 = (tst_t *)malloc(sizeof(tst_t));
    if (NULL == t2) {
        printf("Error: malloc failed\n");
        return;
    }
    *t2 = *t1;   //???????
    free(t1);
    t1 = NULL;
    printf("*t2: %x, t2: %x, &t2: %x\n", *t2, t2, &t2);
    printf("t2->a: %d, t2->b: %d\n", t2->a, t2->b);

    free(t2);
}

int
main(int argc, char *const argv)
{
    func_1();
    func_2();
    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值