#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <string.h>
#define FLUSH myFlush()
struct testInfo {
int grade;
char letterGrade;
char student[30];
};
void menuPrint(int);
void enterScores(struct testInfo **scores, int size);
void printScores(struct testInfo scores[], int size);
char getChoice();
void myFlush();
int main(void) {
struct testInfo *testScores = { 0 };
char userChoice;
int size = 0;
do {
system("clear");
menuPrint(1);
userChoice = getChoice();
switch (userChoice) {
case 'e': case 'E':
system("clear");
menuPrint(2);
printf("Please enter the number of test scores: ");
scanf_s("%d", &size); FLUSH;
testScores = (struct testInfo*)malloc(size * sizeof(struct testInfo));
if (!testScores) { //if there is an error in allocating the memory, exits program.
printf("\nA problem has occured with malloc.");
exit(EXIT_FAILURE);
}
else {
enterScores(&testScores, size);
}
system("pause");
break;
case 'p': case 'P':
printScores(testScores, size);
system("pause");
free(testScores);
break;
case 'l': case 'L':
system("pause");
break;
}
} while (userChoice != 'l' && userChoice != 'L');
return 0;
}//end main
我正在尝试将动态结构传递给函数,以便用户可以写下学生的姓名和他们在考试中获得的考试成绩。我使用了通过引用传递结构的函数,该函数将动态创建和填充结构数组作为参考来确定如何将动态结构传递给函数,但是当用户开始输入时,我可以通过 1在抛出异常之前循环说“访问冲突写入”。
void enterScores(struct testInfo **scores, int size) {
int i;
char name[30];
for (i = 0; i < size; i++) {
printf("\nEnter student's name: ");
fgets(name, 30, stdin);
strcpy(scores[i]->student, name);
printf("\nEnter test score: ");
scanf_s("%i", &scores[i]->grade);
while (scores[i]->grade < 0 || scores[i]->grade > 120) {
printf("\nError in grade range (0-120), try again.");
printf("\nEnter test score: ");
}
//determines letter grade from test Score
if (scores[i]->grade > 90) {
scores[i]->letterGrade = 'A';
}
if (scores[i]->grade < 90 && scores[i]->grade >= 80) {
scores[i]->letterGrade = 'B';
}
if (scores[i]->grade < 80 && scores[i]->grade >= 70) {
scores[i]->letterGrade = 'C';
}
if (scores[i]->grade < 70 && scores[i]->grade >= 60) {
scores[i]->letterGrade = 'D';
}
if (scores[i]->grade < 60 && scores[i]->grade >= 0) {
scores[i]->letterGrade = 'F';
}
}
}//end enterScores