Chapter6.h
#ifndef __CHAPTER_6_
#define __CHAPTER_6_
/*《深入理解C指针》学习笔记 -- 第六章*/
typedef struct __person
{
char* name;
char* title;
unsigned int age;
}person;
/*结构体内存的释放问题*/
void __struct_memory_test();
#endif
Chapter6.cpp
#include "Chapter6.h"
#include <stdio.h>
#include <malloc.h>
#include <string.h>
/*结构体内存的释放问题*/
/*对于结构体内存在指针的情况,我们需要注意怎样正确的使用这个结构体*/
void __struct_memory_test()
{
/*第一种使用结构体的方式*/
person ps;
/*需要为结构体内的指针分配内存才能存储值*/
ps.name = (char*)malloc(sizeof(char) * 16);
strcpy(ps.name, "DLUTBruceZhang");
ps.title = (char*)malloc(sizeof(char) * 10);
strcpy(ps.title, "DLUT");
ps.age = 24;
/*使用完之后需要释放结构体指针的内存*/
free(ps.name);
free(ps.title);
/*第二种使用结构体的方式*/
person* ps2;
/*
首先,需要为结构体申请内存,但是这里需要注意的是,只是为这个结构体申请
内存,结构体内的其他指针需要另外申请别的内存
*/
ps2 = (person*)malloc(sizeof(person));
/*需要为结构体内的指针分配内存才能存储值*/
ps2->name = (char*)malloc(sizeof(char) * 16);
strcpy(ps2->name, "DLUTBruceZhang");
ps2->title = (char*)malloc(sizeof(char) * 10);
strcpy(ps2->title, "DLUT");
ps2->age = 24;
/*
使用完内存后需要释放掉,这里需要注意的是释放内存的顺序
首先应该释放结构体内指针指向的内存,这里是没有先后顺序的,
但是,释放整个结构体的内存一定是最后一步
*/
free(ps2->name);
free(ps2->title);
free(ps2);
}