#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
為什么會發生這種情況?
uj5u.com熱心網友回復:
至少這個問題
錯誤分配
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("Is", name);
struct Student student = {{*name, age}}; 不是需要的初始化。
uj5u.com熱心網友回復:
記憶體分配錯誤。以下代碼將起作用。
#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("Is", name); // 49 '\0' = 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;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/330954.html
下一篇:UDF使用陣列拆分列中的字串
