这是一个程序,假设每次调用addscore时都会创建一个数组,它会在数组的末尾添加一个数组。其余的都是自我解释的。 Scanf似乎是我的崩溃问题,虽然我不知道为什么会这样。因为我在没有使用scanf的情况下选择值2后我的程序仍然崩溃。
#include <stdio.h>
#include<stdlib.h>
#include<time.h>
int deflen;
typedef struct gamedata
{
int score;
}gamedata;
typedef enum boolean {false,true} boolean;
int addscore(struct gamedata scoreArray[])
{
int newscore;
realloc(scoreArray,deflen);
scanf("%d",scoreArray[deflen-1].score);
return 0;
}
int printscore(struct gamedata scoreArray[])
{
int x;
for (x = 0; x <deflen;x++)
{
printf("Player%d, score:%d \n",x+1,scoreArray[x].score);
}
return 0;
}
int findhighest(struct gamedata scoreArray[])
{
int x;
int high;
high = 0;
for (x=0;x<deflen;x++)
{
if (scoreArray[x].score > high){
high = scoreArray[x].score;
}
else{
continue;
}
}
return high;
}
int findavg(struct gamedata scoreArray[])
{
int x;
int sum=0;
int maxLen = deflen;
int avg = 0;
for (x = 0; x <maxLen;x++)
{
sum = sum + scoreArray[x].score;
}
avg = sum/maxLen;
return avg;
}
int main()
{
boolean programEnd = false;
deflen = 10;
gamedata scoreArray[deflen];
srand(time(NULL));
for (int x = 0 ; x<deflen ;x++)
{
scoreArray[x].score = rand() % 20;
printf("%d",scoreArray[x].score);
}
char option;
do{
printf("Please enter an option number: \n"); // this is pretty much what this program is suppose to do.
printf("1.Add a score: \n");
printf("2.Output all score: \n");
printf("3.Find the highest score: \n");
printf("4.Find the average score: \n");
printf("5.End program \n");
///scanf("%s",&option);
option = '2';
printf("%s",option);
switch(option) {
case '1' :
printf("1 step in");
deflen = deflen + 1;
addscore(scoreArray);
break;
case '2' :
printf("2 step in");
printscore(scoreArray);
break;
case '3' :
printf("3 step in");
printf("high score is %d \n",findhighest(scoreArray));
break;
case '4' :
printf("4 step in");
printf("the average score is %d \n",findavg(scoreArray));
break;
case '5' :
printf("5 step in");
programEnd = true;
break;
}
}while (programEnd == false);
return 0;
}
答案 0 :(得分:-1)
程序应该只使用realloc()来调整动态分配的数组!
将数组更改为:
gamedata** scoreArray=malloc(deflen*sizeof(gamedata));
for(int i=0;i<deflen;i++)
scoreArray[i]=malloc(sizeof(gamedata));
并且realloc需要:
scoreArray=realloc(scoreArray,deflen)