【发布时间】:2019-12-04 17:55:29
【问题描述】:
我必须创建一个专注于结构使用的程序。
程序将要求用户输入他稍后将为其添加特定信息(姓名、姓氏、平均成绩)的学生人数。
由于某种原因,当我启动程序时,我输入了我想要的学生人数,然后我输入了第一个学生的信息,然后程序终止了。
这是我尝试过的。
#include <stdio.h>
#include <stdlib.h>
struct student
{
char *name;
char *surname;
float *average;
};
void inputs(struct student *a, int size);
int main()
{
int size;
printf("Enter the number of students: ");
scanf("%d", &size);
struct student *data;
data = (struct student *)malloc(size*sizeof(struct student));
if(data==NULL) {
printf("Cannot allocate memory. The program will now terminate.");
return -1;
}
inputs (data, size);
return 0;
}
void inputs(struct student *a, int size)
{
int j=0;
int i;
for(i=0; i<size; i++) {
printf("Enter the name of the student number %d: ", j+1);
scanf("%s", a->name);
printf("Enter the surname of the student number %d: ", j+1);
scanf("%s", a->surname);
printf("Enter the average grade of the student number %d: ", j+1);
scanf("%f", a->average);
j++;
a++;
}
}
【问题讨论】:
-
这不是导致崩溃的原因,但请注意,您始终只将值写入数组中的第一个学生。
-
你没有为结构中的名字/姓氏变量分配内存
-
@IłyaBursov 但据我所知,按照我的做法,系统会在用户键入字符时分配所需的内存。例如,如果我写 int *ptr=john 程序将自动为包括 \0 在内的 5 个字符分配内存。
-
@Giannis
the system allocates the needed memory as the user types in the characters这是错误的。 -
@Giannis 类型是指针,所以它只会为指针分配 4 个字节,系统不知道你将在其中存储多少个符号
标签: c