小练习,新手建议练练手哦

来源:互联网 发布:网络攻击监测网站 编辑:程序博客网 时间:2024/04/30 05:16

在堆上分配一个学生结构体,键盘输入学生的编号、姓名、成绩,提示是否继续输入,选择Y继续输入 选择N 显示输入的所有学员信息,用varglind检查内存,注意内存泄露。

#include<stdio.h>#include<assert.h>#include<stdlib.h>#include<string.h>typedef struct student{    int id;    char name[30];    double score;}Stu;int count = 0;void initStruct(Stu* p){    printf("请输入学生的信息:(学号、姓名、成绩):");    char ch = '\0';    int i = 0;    scanf("%d %s %lf",&(p[count].id),p[count].name,&(p[count].score));    count++;    printf("Y继续,n退出\n");}void outStruct(Stu* p){    int i = 0;    for(i = 0;i < count;i++){        printf("%d\t\t%s\t\t%.2lf\n",p[i].id,p[i].name,p[i].score);    }}int main(void){    Stu* p = (Stu*)malloc(sizeof(Stu)*10);    assert(p);    memset(p , 0 ,sizeof(Stu) * 10);    char ch = '\0';    int flag = 0;    while(1){        initStruct(p);        while(getchar() != '\n');        ch = getchar();        if(ch == 'y' || ch == 'Y'){            flag = 1;        }        if(ch == 'n' || ch == 'N'){            flag = 0;        }        if(!flag){            outStruct(p);            break;        }else if (flag == 1){            continue;        }    }    free(p);    p = NULL;    return 0;}
原创粉丝点击