该程序应该捕获用户输入到结构中的输入,然后打印出给定信息的直方图.到目前为止一切正常,除了当我尝试打印直方图时,无论学生的成绩如何,所有'*'字符都属于F级.我认为正在发生的是学生的数组索引被传递而不是实际变量本身,但我很困惑,因为在直方图打印之前的输出中它显示正确的值.有什么建议?
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 28
#define MAXGRADE 100
struct studentData{
char studentID[MAXSIZE];
char studentName[MAXSIZE];
int examPercent;
} studentRecords[MAXSIZE];
// function prototype for histogram
void displayHist(struct studentData *records, int classSize);
int main()
{
int i, students = -1;
//struct studentData *studentRecords[MAXSIZE];
while(students < 0 || students > MAXSIZE)
{
printf("Please enter the number of students in your class:\n");
scanf("%d", &students);
if(students > MAXSIZE || students <= 0)
{
printf("Try again..\n");
scanf("%d", &students);
}
}
for(i=0;i<students;i++) {
printf("Please enter the student #%d's lastname:\n", i+1);
scanf("%s", &studentRecords[i].studentID);
printf("Please enter the student #%d's ID#:\n", i+1);
scanf("%s", &studentRecords[i].studentName);
printf("Please enter the student's exam percent:\n");
scanf("%d", &studentRecords[i].examPercent);
}
//This is just here to view the input...
for(i=0;i<students;i++) {
printf("Student #%d's name is %s\n", i+1, studentRecords[i].studentName);
printf("student #%d's ID#:%s\n", i+1, studentRecords[i].studentID);
printf("student #%d's grade was %d\n", i+1, studentRecords[i].examPercent);
}
displayHist(&studentRecords[students], students);
return 0;
}
void displayHist(struct studentData *records, int classSize)
{
int i;
printf("A:");
for(i=0;i<classSize;i++)
{
if(records[i].examPercent >=90)
{
printf("*");
}
}
printf("\n");
printf("B:");
for(i=0;i<classSize;i++)
{
if(records[i].examPercent< 90 && records[i].examPercent >= 80)
{
printf("*");
}
}
printf("\n");
printf("C:");
for(i=0;i<classSize;i++)
{
if(records[i].examPercent < 80 && records[i].examPercent >= 70)
{
printf("*");
}
}
printf("\n");
printf("D:");
for(i=0;i<classSize;i++)
{
if(records[i].examPercent< 70 && records[i].examPercent >= 60)
{
printf("*");
}
}
printf("\n");
printf("F:");
for(i=0;i<classSize;i++)
{
if(records[i].examPercent < 60)
{
printf("*");
}
}
}
Run Code Online (Sandbox Code Playgroud)
displayHist(&studentRecords[students], students);
Run Code Online (Sandbox Code Playgroud)
&studentRecords[students]是数组之后的地址studentRecords。在 中 displayHists,访问records[i]将尝试取消引用studentRecords[students+i],这超出了数组的范围。
正确的调用可能是:
displayHist(&studentRecords[0], students);
Run Code Online (Sandbox Code Playgroud)
这相当于:
displayHist(studentRecords, students);
Run Code Online (Sandbox Code Playgroud)
顺便说一下,不需要使用&with ,因为和scanf可能有不同的内存表示。char *char (*)[]char *