#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <string.h> typedef struct Peo { int age; char name[32]; }peo; void copy1(peo *obj1, peo *obj2) { *obj1 = *obj2;//可以直接整体赋值 } void copy2(peo *obj1, peo *obj2) { obj1->age = obj2->age;//也可以单个赋值 strcpy(obj1->name, obj2->name); } int main() { peo a = {1,"xiaoming"}; peo aa = a;//支持整体赋值,故后面指针解引用也可以整体赋值 printf("%d %s ", aa.age, aa.name); peo aaa; copy2(&aaa, &a); printf("%d %s ", aaa.age, aaa.name); }
模拟开辟内存二级结构体指针:
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <string.h> #include <stdlib.h> typedef struct Peo { int age; char *name; }peo; peo* test(peo** obj) { *obj = (peo*)malloc(sizeof(peo)); if (*obj == NULL) return NULL; else { (*obj)->age = 10; (*obj)->name = "xiaohong"; return *obj; } } void myfree(peo* obj) { if (obj != NULL) { free(obj); obj = NULL; } } int main() { peo *p1=NULL; test(&p1); printf("%d %s ", p1->age, p1->name); myfree(p1); }