0

After the enter the first answer the code crashes. Also it states that the memory is unsuccessful allocated. How can i fix this?

#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);

based on the number of questions the user wishes to take, allocate enough memory to hold question data

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;

} //end main

David Robinson
  • 77,383
  • 16
  • 167
  • 187
user1251302
  • 91
  • 2
  • 10

2 Answers2

0

Might this be the answer:

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

The '-' should be an '='.

Kevin Tran
  • 80
  • 2
0

answer[i]= num1[i] * num2[i]

should read

answer[i] == num1[i] * num2[i]

= is for assignments, == is for comparisons.

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

should read

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

If there are other problems, you need to be more specific than "the program messes up".

Also, don't cast the return value of malloc or calloc. Read Do I cast the result of malloc? .

Community
  • 1
  • 1
Dan
  • 10,531
  • 2
  • 36
  • 55
  • When the program give me the "Quiz results" there is random numbers for the three section: Question, Your answer, and correct. – user1251302 Mar 12 '12 at 18:28