qfedu-c-level/day12/d21.c

31 lines
714 B
C
Raw Permalink Normal View History

// 浅拷贝
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct POS
{
int *x;
int *y;
};
int main()
{
struct POS *p1 = malloc(sizeof(struct POS));
p1->x = (int *)malloc(sizeof(int));
p1->y = (int *)malloc(sizeof(int));
*(p1->x) = 20;
*(p1->y) = 30;
printf("point1 x=%d,y=%d\n", *(p1->x), *(p1->y));
struct POS *p2 = malloc(sizeof(struct POS));
memcpy(p2, p1, sizeof(struct POS)); // 浅拷贝,只拷贝了结构体本身,没有拷贝结构体成员
*(p2->x) = 200;
printf("point2 x=%d,y=%d\n", *(p2->x), *(p2->y));
printf("point1 x=%d,y=%d\n", *(p1->x), *(p1->y));
free(p1->x);
free(p1->y);
free(p1);
free(p2);
return 0;
}