C程序在最后一次scanf / last循环后崩溃,(琐事游戏)。
struct myQuiz*quizInput(int *nrQ)
{
int i, nrofrecords = 0;
struct myQuiz *Quiz = (struct myQuiz*)malloc(sizeof (struct myQuiz)**nrQ);
printf("How many Questions?\n");
scanf_s("%d", nrQ);
for (i = 0; i < *nrQ; i++) //for-loop för att skriva in påståenden
{
printf("Trivia input: ");
fflush(stdin);
fgets(Quiz[i].qQuest, 100, stdin);
nrofrecords = nrofrecords + 1;
fflush(stdin);
printf("Enter answer '1'(yes) or '0' (no): ");
scanf_s("%d", &Quiz[i].qAns);
fflush(stdin);
printf("Enter the difficulty (1-5)?: ");
scanf_s("%d", &Quiz[i].qDiff);
}
return Quiz;
}
答案 0 :(得分:2)
nRQ
是基于此值
struct myQuiz *Quiz = (struct myQuiz*)malloc(sizeof (struct myQuiz)**nrQ);
在malloc之后询问实际问题值,因此如果传递给函数的初始值小于问题,则会发生内存损坏。 您需要先获取输入,然后再分配内存。
printf("How many Questions?\n");
scanf_s("%d", nrQ);
答案 1 :(得分:1)
the code is using some trash from nrQ for the malloc
before nrQ variable is set.
returned values from I/O statements
must be checked to assure successful operation.
the user prompts fail to clearly indicate what the user is to input
suggest:
printf("Please indicate how many Questions you will enter?\n");
if(1 != scanf_s("%d", nrQ))
{ // then, scanf_s failed
perror( "scanf_s for number questions failed" );
return( NULL );
}
// implied else, scanf_s successful
struct myQuiz *Quiz = NULL;
if( NULL == (Quiz = malloc(sizeof (struct myQuiz)*(*nrQ)) )) )
{ // then, malloc failed
perror( "malloc array of struct myQuiz failed" );
return( NULL );
}
// implied else, malloc successful
printf("\nNote: max question length: %d\n", sizeof(struct myQuiz.qQuest) );
答案 2 :(得分:0)
您必须先初始化*nrQ
struct myQuiz*quizInput(int *nrQ)
{
int i, nrofrecords = 0;
struct myQuiz *Quiz; // = malloc(sizeof (struct myQuiz)**nrQ); you need to initialize *nrQ first
printf("How many Questions?\n");
scanf_s("%d", nrQ);
Quiz = malloc(sizeof (struct myQuiz)**nrQ);
for (i = 0; i < *nrQ; i++) //for-loop för att skriva in påståenden
{
printf("Trivia input: ");
fgets(Quiz[i].qQuest, 100, stdin);
nrofrecords = nrofrecords + 1;
printf("Enter answer '1'(yes) or '0' (no): ");
scanf_s("%d", &Quiz[i].qAns);
printf("Enter the difficulty (1-5)?: ");
scanf_s("%d", &Quiz[i].qDiff);
}
return Quiz;
}
另外
malloc
fflush(stdin)