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

    技术2022-07-10  138

    # 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; }
    Processed: 0.011, SQL: 9