严格遵守题目要求,规范代码!
复习指针方式,提供大家参考学习交流~
参考代码如下:
#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; }
0.0分
24 人评分
#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),
if (stutmp == NULL) { return NULL; } 这是用来做什么的? 还有下面的
stutmp->id = (char*)malloc(strlen(idtmp) + 1);请问这里为什么要+1?
教你夺冠 2018-05-16 19:32:14 |
+1是 字符串的结束符\0啊