深入理解 C 指针阅读笔记 -- 第六章

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);
}


评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值