#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct Student {
char name[50];
int age;
} student;
int main() {
char name[50];
int age;
// Requirement values
char stop[] = "stop";
int check = 1;
int countOfStudents = 0;
// Array with students
student* students = malloc(countOfStudents);
while(check) {
scanf("%s", &name);
if(!strcmp(name, stop) == 0) {
scanf(" %i", &age);
struct Student student = {*name, age};
strcpy(students[countOfStudents].name, student.name);
students[countOfStudents].age = student.age;
countOfStudents++;
} else {
printf("You wrote stop n");
check = 0;
}
}
for (int i = 0; i < countOfStudents; ++i) {
printf("Name = %s , Age = %i", students[i].name, students[i].age);
printf("n");
}
return 0;
}
我有一个学生数组。每个学生都是一个结构体,并有一个名称& &;的年龄。我必须注册每个学生,直到用户写"停止"。
输入:
test
12
stop
输出如下:
You wrote stop
ogram Files (x86)
Name = t♀ , Age = 0
为什么会发生这种情况?
至少这个问题
<<p>错误分配/strong>int countOfStudents = 0;
student* students = malloc(countOfStudents);
分配零内存。
试
int countOfStudents = 0;
int Students_MAX = 100;
student* students = malloc(sizeof *students * Students_MAX);
和极限迭代:
while(countOfStudents < Students_MAX && check)
最好使用宽度限制
char name[50];
...
// scanf("%s", name);
scanf("%49s", name);
struct Student student = {{*name, age}};
不是需要初始化的
内存分配错误。下面的代码可以工作。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct Student
{
char name[50];
int age;
} student;
int main()
{
char name[50];
int age;
char stop[] = "stop";
int check = 1;
int countOfStudents = 0;
student* students = NULL;
while(check)
{
scanf("%49s", name); // 49 + ' ' = 50
if(!strcmp(name, stop) == 0)
{
scanf(" %i", &age);
if(!students)
{
students = (student*) malloc(sizeof(student*)); // allocating for the first
}
else
{
students = (student*) realloc(students, sizeof(student*)); // allocating
}
strcpy(students[countOfStudents].name, name);
students[countOfStudents].age = age;
countOfStudents++;
}
else
{
printf("You wrote stop n");
check = 0;
}
}
for (int i = 0; i < countOfStudents; ++i)
{
printf("Name = %s , Age = %i", students[i].name, students[i].age);
printf("n");
}
free(students);
students = NULL;
return 0;
}