I a function that allows you to add question to a game. I use realloc to increase the memory so i can store more questions.
Script:
struct Question* AddQuestions(int* amountQuest){
struct Question* questionsLocation = NULL;
int startQuestion = 0;//How many question from before.
int amount;
if (*amountQuest > 0){
startQuestion = *amountQuest;
}
system("cls");
printf("How many statement do you want to add? ");
scanf_s("%d", &amount);
printf("\n");
*amountQuest = amount + startQuestion;//Total amount of questions
//Realloc or allocate new block if null
questionsLocation = (struct Question*)realloc(questionsLocation,*amountQuest * sizeof(struct Question));
if (questionsLocation != NULL){ // Check if allocating worked
//Add questions
for (int i = startQuestion; i < *amountQuest; i++){//Starts att startQuestion so I don't override the old question.
printf("Statement %d: ", i + 1);
fflush(stdin);
fgets(questionsLocation[i].question, 200, stdin);
printf("Dificulty: ");
scanf_s("%d", &questionsLocation[i].difficult);
printf("Right answer [1 = true / 0 = false] : ");
scanf_s("%d", &questionsLocation[i].rightAnswer);
printf("\n");
}
return questionsLocation;
}
else{
printf("Problem occurred, try again");
fflush(stdin);
getchar();
return NULL;
}
}
When I add the new questions the old get override.
Image: When I add the first questions without problem
Image: When I add more questions and I get problem.