C语言第十一天--------------------一个用堆区写的学生管理系统

数据存储区:
1、动态区。
2、静态区。
3、堆区(程序员空间):用户通过API(malloc)申请空间,也可以释放(free)空间。

申请堆区:void* malloc(size_t) ;申请堆区的长度
realloc(void* old,sizet_t)
返回值:申请空间首地址,如果为NULL,则申请失败
使用堆区:只能指针法
释放空间:不能多次释放同一空间
free(void*)
应用:
申请一个空间
malloc(sizeof(类型))
申请一个数组空间:
malloc(sizeof(类型)*n)
实现一个动态数组:通过堆区的特性来申请不定长空间
1.申请一块大空间,将老空间赋值到此空间
2.释放老空间
块空间赋值:
memecpy();

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
//重命名
typedef char bool;

//定义学生结构体
struct score
{
	int c;//C语言
	int m;//数学
};
typedef struct student
{
	char name[10];  //名字
	char sex;	//性别
	struct score sc;//成绩
}student,*pstudent;
//定义学生系统
typedef struct
{
	pstudent ps;
	int num;
	int size;
}stus,*pstus;

//增加:记录一个学生
bool add(pstus pt,char* name,char sex,int c,int m)
{
	pstudent newps=NULL;
	if(pt->size==pt->num)
	{
		pt->size+=5;
		newps=malloc(sizeof(student)*pt->size);
		memcpy(newps,pt->ps,sizeof(student)*pt->num);
		free(pt->ps);
		pt->ps=newps;
	}
	strcpy(pt->ps[pt->num].name,name);
	pt->ps[pt->num].sex=sex;
	pt->ps[pt->num].sc.c=c;
	pt->ps[pt->num].sc.m=m;
	pt->num++;
	return 1;
}
bool delete(pstus pt,int n)
{
	if(pt->num<n && n<1)
		return 0;
	int i;
	for(i=n;i<=pt->num;i++)
		pt->ps[i-1]=pt->ps[i];
	pt->num--;
	printf("删除第%d个元素成功\n",n);
	return 1;
}
bool update(pstus pt,int n,char* name,char sex,int c,int m)
{
	if(pt->num<n && n<1)
		return 0; 
	strcpy(pt->ps[n-1].name,name);
	pt->ps[n-1].sex=sex;
	pt->ps[n-1].sc.c=c;
	pt->ps[n-1].sc.m=m;
	printf("修改第%d个元素成功\n",n);
	return 1;	
}
bool find(pstus pt,char* name)
{
	int i;
	for(i=0;i<pt->num;i++)
	{
		if(!strcmp(name,pt->ps[i].name))
		{	
			printf("%s存在,是第%d个学生\n",name,i+1);
			return 1;
		}
	}
	printf("查找失败\n");
	return 0;
}
void InitSys(pstus pt)
{
	pt->ps=NULL;
	pt->size=0;
	pt->num=0;
}
void list(pstus pt)
{
	int i=0;
	printf("|---name---|-sex-|--c--|--m--|\n");
	while(i<pt->num)
	{
		printf("|%-10s|%-5c|%-5d|%-5d|\n",pt->ps[i].name,pt->ps[i].sex,
					  pt->ps[i].sc.c,pt->ps[i].sc.m);
		i++;
	}
	printf("|----------|-----|-----|-----|\n");
}
int main()
{
	stus s;	
	InitSys(&s);
	add(&s,"lifei",'m',100,100);
	add(&s,"zh",'w',100,100);	
	find(&s,"zh");
	list(&s);
	update(&s,2,"hz",'m',100,100);
	list(&s);
	delete(&s,2);
	list(&s);
	free(s.ps);
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值