struct Teacher { char *name; int age; }; void test02() { struct Teacher teacher1; teacher1.name = malloc(sizeof(char)* 64); memset(teacher1.name, 0, 64); strcpy(teacher1.name, "aaa"); teacher1.age = 20; struct Teacher teacher2; teacher2.name = malloc(sizeof(char)* 128); memset(teacher2.name, 0, 128); strcpy(teacher2.name, "bbbbbbbbbbbbb"); teacher2.age = 30; printf("Name:%s Age:%d\n", teacher1.name,teacher1.age); printf("Name:%s Age:%d\n", teacher2.name, teacher2.age); printf("teacher1 size: %d\n",sizeof(teacher1)); printf("teacher2 size: %d\n", sizeof(teacher2)); //赋值操作 //不使用默认的结构体赋值行为 //teacher1 = teacher2; //如果结构体内部有指针指向堆内存,那么就不能使用编译器默认的赋值行为,应该手动控制赋值过程。 //---------------------------------------------- if (teacher1.name != NULL) { free(teacher1.name); teacher1.name = NULL; } teacher1.name = malloc(strlen(teacher2.name) + 1); strcpy(teacher1.name, teacher2.name); teacher1.age = teacher2.age; //---------------------------------------------- printf("---------------\n"); printf("Name:%s Age:%d\n", teacher1.name, teacher1.age); printf("Name:%s Age:%d\n", teacher2.name, teacher2.age); //释放堆内存 if (teacher1.name != NULL) { free(teacher1.name); teacher1.name = NULL; } if (teacher2.name != NULL) { free(teacher2.name); teacher2.name = NULL; } } 详细注释这段代码,每一句的作用意义都解释一下
时间: 2024-04-16 21:28:12 浏览: 71
struct2json:JSON和C结构之间的快速转换库。 为C实现结构序列化和反序列化。 C结构体与JSON快速互转库,快速实现C结构体的序列化及反序列化
下面是对代码中每一句的详细注释解释:
```c
struct Teacher
{
char *name;
int age;
};
```
定义了一个结构体类型Teacher,包含name和age两个成员。
```c
void test02()
{
struct Teacher teacher1;
teacher1.name = malloc(sizeof(char) * 64);
memset(teacher1.name, 0, 64);
strcpy(teacher1.name, "aaa");
teacher1.age = 20;
// 创建teacher1结构体变量,为name分配64字节的内存,并将其初始化为空字符串。
// 然后将名字赋值为"aaa",年龄赋值为20。
struct Teacher teacher2;
teacher2.name = malloc(sizeof(char) * 128);
memset(teacher2.name, 0, 128);
strcpy(teacher2.name, "bbbbbbbbbbbbb");
teacher2.age = 30;
// 创建teacher2结构体变量,为name分配128字节的内存,并将其初始化为空字符串。
// 然后将名字赋值为"bbbbbbbbbbbbb",年龄赋值为30。
printf("Name:%s Age:%d\n", teacher1.name, teacher1.age);
printf("Name:%s Age:%d\n", teacher2.name, teacher2.age);
// 打印输出teacher1和teacher2的名字和年龄。
printf("teacher1 size: %d\n", sizeof(teacher1));
printf("teacher2 size: %d\n", sizeof(teacher2));
// 打印输出teacher1和teacher2占用的内存大小。
if (teacher1.name != NULL)
{
free(teacher1.name);
teacher1.name = NULL;
}
teacher1.name = malloc(strlen(teacher2.name) + 1);
strcpy(teacher1.name, teacher2.name);
teacher1.age = teacher2.age;
// 释放teacher1之前分配的内存,然后为name重新分配内存,并将其赋值为teacher2的name。
// 最后将teacher1的年龄赋值为teacher2的年龄。
printf("---------------\n");
printf("Name:%s Age:%d\n", teacher1.name, teacher1.age);
printf("Name:%s Age:%d\n", teacher2.name, teacher2.age);
// 打印输出修改后的teacher1和未修改的teacher2的名字和年龄。
if (teacher1.name != NULL)
{
free(teacher1.name);
teacher1.name = NULL;
}
if (teacher2.name != NULL)
{
free(teacher2.name);
teacher2.name = NULL;
}
// 释放teacher1和teacher2分配的内存。
}
```
希望以上解释对你有帮助!如果还有其他问题,请随时提问。
阅读全文