【c语言】struct赋值case

struct 变量高效赋值的一个例子:

# cat test.c
#include 
#include 

typedef struct _tag_t_
{
    int i;
    int j;
} t_t;

typedef struct _tag_tst_
{
    int a;
    int b;
    t_t t;
} tst_t;


void func(void)
{
    tst_t *tst1 = NULL;
    tst_t *tst2 = NULL;
    t_t t1 = {0};

    tst1 = (tst_t *)malloc(sizeof(tst_t));
    if (NULL == tst1) {
        printf("malloc failed\n");
        return;
    }
    tst1->a = 10;
    tst1->b = 20;
    tst1->t.i = 1;
    tst1->t.j = 2;

    printf("TST<> tst1: a = %d, b = %d, t.i = %d, t.j = %d\n",
            tst1->a, tst1->b, tst1->t.i, tst1->t.j);

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

    *tst2 = *tst1;

    free(tst1);
    printf("TST tst2: a = %d, b = %d, t.i = %d, t.j = %d\n",
            tst2->a, tst2->b, tst2->t.i, tst2->t.j);

    t1 = tst2->t;
    free(tst2);

    printf("TSTt> t1: t1.i = %d, t1.j = %d\n", t1.i, t1.j);
}


int main(int argc, char *const argv[])
{
    func();
    return 0;
}

你可能感兴趣的:(C语言)