C语言中malloc和Free的使用

malloc分配内存,free释放内存,结构体中的指针和结构体指针要通过malloc分配,使用完后,通过free释放并置于NULL,

 

 

#include<iostream>
using namespace std;
typedef struct _Birthday
{
	int day;
	int month;
	int year;

} Birthday;
typedef struct _Student
{
	int schoolNumber;
	char *name;
	Birthday year;
} Student;


typedef enum _Color
{
	red,
	blue,
	white,
	yellow
} Color;

//结构体数组
struct student
{
	int mum;
	char name[20];
	char sex;
	int age;
	float score;
	char addr[30];
}stu[3] = {{11,"HHH", 'M', 18, 87.5, "Road"},{10101,"Li Lin", 'M', 18, 87.5, "Road"},{10101,"Lin", 'M', 18, 87.5, "103 Beijing Road"}};

int main()
{
	Student std;
	//分配内存空间
	std.name=(char *)malloc(20*sizeof(char));
	strcpy(std.name,"test");
	std.year.day=10;
	std.year.month=12;
	std.year.year=2012;
	cout<<std.name<<endl;
	cout<<std.year.year<<"年"<<std.year.month<<"月"<<std.year.day<<endl;


	Student *stdOne;
	//分配内存空间
	stdOne=(Student *)malloc(sizeof(Student));
	stdOne->name=(char *)malloc(20*sizeof(char));
	strcpy(stdOne->name,"testOne");

	//释放分配的内存
	free(std.name);
	free(stdOne->name);
	free(stdOne);


	//防止野指针的产生
	std.name=NULL;
	stdOne->name=NULL;
	stdOne=NULL;


	//枚举类型
	Color color=red;
	cout<<"Color:"<<color<<endl;
	return 0;
}
 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值