該程序背後的思想是爲學生信息聲明一個數據結構,然後讓用戶將輸入信息輸入數據結構的每個字段中,以便輸入數量的學生。我的問題是程序停止工作,當我輸入名字。哪裏不對?感謝您的時間。將用戶輸入值分配給分配的內存
//Inclusion of necessary header files
#include <stdio.h>
#include <stdlib.h>
//Data structure declaration
struct student{
char firstName[20];
char lastName[20];
char id[10];
char gender;
int age;
double gpa;
};
//Function prototypes
void readStudentsInformation(struct student *, int size);
void outputStudents(struct student *, int size);
double averageGPA(struct student *, int size);
void sortByLastName(struct student *, int size);
void sortByGPA(struct student *, int size);
//Entry point
int main()
{
//Variable delcaration
int size;
struct student *ptr;
//Input prompt and function
printf("How many students?\n");
scanf_s("%d", &size);
//Allocation memory for struct student times the number of students and assigning it to a struct student pointer for external function modification
ptr = (struct student*)malloc(sizeof(struct student)*size);
//readStudentsInformation Function call
readStudentsInformation(ptr, size);
//Exit sequence
return 0;
}
//This functions reads the information for all the students from the keyboard, taking the class size through the pointer method and struct student from main
void readStudentsInformation(struct student *ptr, int size)
{
//For loop controller declaration
int i;
//Function message
printf("Student Information Form\n");
//This for loop increments the "index" of each students info location where user input is stored
for(i=0;i<size;i++)
{
//Each field has it's appropriate input limit
printf("Please enter Student %d's First Name(20 characters).\n", i+1);
scanf_s("%20s", ptr[i].firstName);
printf("Please enter Student %d's Last Name(20 characters).\n", i+1);
scanf_s("%20s", ptr[i].lastName);
printf("Please enter Student %d's ID(10 characters).\n",i+1);
scanf_s("%10s", ptr[i].id);
printf("Please enter Student %d's gender(M/F).\n",i+1);
scanf_s("%c", ptr[i].gender);
printf("Please enter Student %d's age.\n",i+1);
scanf_s("%3d", ptr[i].age); //Only 3 digits can be put in at a time
printf("Please enter Student %d's GPA.\n", i+1);
scanf_s("%.1lf", ptr[i].gpa); //From the lab it can be seen that no more than one decimal place is featured, so the same is done here
}
//Exit to main
return;
}
我已經調整了scanf_s的,但該計劃似乎仍在崩潰。我不認爲這是正確的處理。如果我聲明一個類型爲struct student的數組並將其數組大小設置爲用戶輸入,會怎麼樣? – sourcecodedysfunction