我想用C做一个数学测验程序,到目前为止我有这个但我无法弄清楚出了什么问题

时间:2012-03-12 18:15:01

标签: malloc

输入第一个答案后,代码崩溃了。 它还说明内存分配不成功。我怎样才能解决这个问题?

#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 Quiz\n");
 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 unsucessful\n");
}  //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 Results\n");
 printf("Question\tYour Answer\tCorrect");

 for(i=0; i<response; i++);
 {
          if(result[i] == 'c')
          {
                        printf("%d * %d\t\t%d\t\tYES",num1[i],num2[i],answer[i]);
          }

          else
          {
                        printf("%d * %d\t\t%d\t\tNo",num1[i],num2[i],answer[i]);
        }
} //end for loop      



free(num1);
free(num2);
free(answer);
free(result);

system("pause");
return 0;

} //结束主要

2 个答案:

答案 0 :(得分:0)

这可能是答案:

result - (char *)calloc(response,sizeof(char));

' - '应该是'='。

答案 1 :(得分: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));

如果还有其他问题,你需要比“程序混乱”更具体。

此外,请勿转换malloccalloc的返回值。阅读Do I cast the result of malloc?