严格遵守题目要求,规范代码!

复习指针方式,提供大家参考学习交流~


参考代码如下:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

//定义一个学生结构体
typedef struct
{
    char *id;
    char *name;
    int score1;
    int score2;
    int score3;
} Stu;

//1 输入一个Stu信息 返回一个Stu指针
Stu *inputStu()
{
    Stu *stutmp = (Stu*)malloc(sizeof(Stu));
    if (stutmp == NULL)
    {
        return NULL;
    }

    char idtmp[100];
    scanf("%s", idtmp);
    stutmp->id = (char*)malloc(strlen(idtmp) + 1);
    if (stutmp->id == NULL)
    {
        return NULL;
    }
    strcpy(stutmp->id, idtmp);

    char nametmp[100];
    scanf("%s", nametmp);
    stutmp->name = (char*)malloc(strlen(nametmp) + 1);
    if (stutmp->name == NULL)
    {
        return NULL;
    }
    strcpy(stutmp->name, nametmp);

    scanf("%d", &stutmp->score1);
    scanf("%d", &stutmp->score2);
    scanf("%d", &stutmp->score3);

    return stutmp;
}

//2 打印学生信息
void printStu(Stu *stu)
{
    printf("%s,%s,%d,%d,%d\n", stu->id, stu->name, stu->score1, stu->score2, stu->score3);
}

//3 释放一个Stu结构
void freeStu(Stu *stu)
{
    if (stu == NULL)
        return;

    free(stu->id);
    free(stu->name);
    free(stu);
}

int main()
{
    int N;
    scanf("%d", &N);
    if (N >= 100)
    {
        return -1;
    }

    //定义一个结构体指针数组,存放N个指针
    Stu *student[N];
    //1 输入
    int i;
    for (i = 0; i < N; i++)
    {
        student[i] = inputStu();
    }

    //2 打印
    for (i = 0; i < N; i++)
    {
        printStu(student[i]);
    }

    //3 释放
    for (i = 0; i < N; i++)
    {
        freeStu(student[i]);
    }

    return 0;
}


点赞(8)
 

0.0分

21 人评分

C语言网提供由在职研发工程师或ACM蓝桥杯竞赛优秀选手录制的视频教程,并配有习题和答疑,点击了解:

一点编程也不会写的:零基础C语言学练课程

解决困扰你多年的C语言疑难杂症特性的C语言进阶课程

从零到写出一个爬虫的Python编程课程

只会语法写不出代码?手把手带你写100个编程真题的编程百练课程

信息学奥赛或C++选手的 必学C++课程

蓝桥杯ACM、信息学奥赛的必学课程:算法竞赛课入门课程

手把手讲解近五年真题的蓝桥杯辅导课程

评论列表 共有 9 条评论

dotcpp0780032 5月前 回复TA
free(stu->id);
    free(stu->name);
    free(stu);  为什么写的是这三个语句
3g芯片 1年前 回复TA
#include <stdio.h>
struct Students{
    char a[10];
    char b[10];
    char c[10];
    char d[10];
    char e[10];
};
struct Students *input(struct Students *s);
void print(struct Students *s);
void main( void )
{
    int num;
    int i;

    scanf("%d",&num);
    struct Students STU[num];
    struct Students *p;
    struct Students *p1[num];

    for (i = 0; i < num; i++)
    {
        p = &STU[i];
        p1[i] = input(p);
    }
    for (i = 0; i < num; i++)
    {
        print( p1[i] );
    }

}

struct Students *input(struct Students *s)
{
    scanf("%s %s %s %s %[^\n]",&(s->a), &(s->b),
侯加奇 5年前 回复TA
主函数定义的Stu *student[N]在vs2019编译器会出错,怎么解决
侯加奇 5年前 回复TA
@maxiao malloc内存申请失败返回NULL
wanghg 6年前 回复TA
@maxiao 空的话内存申请失败
maxiao 6年前 回复TA
@maxiao 判断内存申请是否成功?   那什么情况下申请失败
maxiao 6年前 回复TA
if (stutmp == NULL)
    {
        return NULL;
    }     这是用来做什么的? 还有下面的
教你夺冠 6年前 回复TA
@kimcho +1是 字符串的结束符\0啊
kimcho 6年前 回复TA
stutmp->id = (char*)malloc(strlen(idtmp) + 1);请问这里为什么要+1?