输入第一个答案后,代码崩溃。它还表示内存分配不成功。我该怎么解决这个问题?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
int main(void)
{
int i;
srand(time(NULL));
int *num1;
int *num2;
int response;
int *answer;
char *result;
printf("nMath Quizn");
printf("Enter # of problems: ");
scanf("%d", &response);
根据用户希望回答的问题数量,分配足够的内存来保存问题数据
num1 = (int *)calloc(response, sizeof(int));
num2 = (int *)calloc(response, sizeof(int));
answer = (int *)calloc(response, sizeof(int));
result - (char *)calloc(response, sizeof(char));
if(num1 == NULL || num2 == NULL || answer == NULL || result == NULL)
{
printf("memory allocation unsucessfuln");
} //end if
for(i=0; i<response; i++)
{
num1[i] = (rand() % 12)+1;
num2[i] = (rand() % 12)+1;
printf("%d * %d = ", num1[i], num2[i]); //somewhere at this point the program messes up
scanf("%d", &answer[i]);
if(answer[i]= num1[i] * num2[i])
{
result[i] = 'c';
}
else
{
result[i] = 'i';
}
} //end for loop
printf("Quiz Resultsn");
printf("QuestiontYour AnswertCorrect");
for(i=0; i<response; i++);
{
if(result[i] == 'c')
{
printf("%d * %dtt%dttYES",num1[i],num2[i],answer[i]);
}
else
{
printf("%d * %dtt%dttNo",num1[i],num2[i],answer[i]);
}
} //end for loop
free(num1);
free(num2);
free(answer);
free(result);
system("pause");
return 0;
}//结束主
answer[i]= num1[i] * num2[i]
应读取
answer[i] == num1[i] * num2[i]
=
用于分配,==
用于比较。
和result - (char *)calloc(response, sizeof(char));
应读取
result = (char *)calloc(response, sizeof(char));
如果还有其他问题,你需要比"程序搞砸了"更具体。
另外,不要强制转换malloc
或calloc
的返回值。请阅读我是否投射malloc的结果。
这可能是答案吗:
result-(char*)calloc(response,sizeof(char));
"-"应该是一个"="。