我是一个允许您向游戏添加问题的功能。我使用realloc来增加内存,这样我就可以存储更多问题。
脚本:
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;
}
}
当我添加新问题时,旧的获取覆盖。 图片:当我添加第一个问题时没有问题
图片:当我添加更多问题时,我遇到了问题。
答案 0 :(得分:2)
您的代码不会尝试保留早期的问题。它始终使用realloc()
指针调用NULL
,从而产生全新的分配:
struct Question* questionsLocation = NULL;
/* ...there are no assignments to questionsLocation here... */
questionsLocation = (struct Question*)realloc(questionsLocation,
*amountQuest * sizeof(struct Question));
要保留数据,您需要保留从realloc()
获得的指针,并在下次重新分配内存时使用它。
执行此操作的一种方法是更改函数以questionsLocation
作为参数:
struct Question* AddQuestions(int* amountQuest, struct Question* questionsLocation) {
...
questionsLocation = (struct Question*)realloc(questionsLocation, ...);
...
return questionsLocation;
}
然后像这样使用它:
int amountQuest = 0;
struct Question* questionsLocation = NULL;
...
questionsLocation = AddQuestion(&amountQuest, questionsLocation);
(为清楚起见,我没有包含任何错误检查。你可能想添加一些。)
答案 1 :(得分:1)
您需要将questionsLocation
和startQuestion
声明为static
,这样他们才能将其值从一次调用保留到下一次。
static struct Question* questionsLocation = NULL;
static int startQuestion = 0;//How many question from before.
但是,更好的方法是让您的函数将这些值作为参数接收。
struct Question* AddQuestions(int* amountQuest, structQuestion*questionsLocation, int startQuestion){
答案 2 :(得分:0)
realloc()的正确方法是
尺寸应该能够容纳您之前的问题以及新问题。对于Eg:
n = num_of_old_questions + num_of_new_questions;
struct Question *temp = realloc(questionsLocation, sizeof(struct Question) * n);
if(temp != NULL)
{
questionsLocation = temp;
}
如果realloc()
失败,那么您也将丢失原始指针数据,因此最好使用temp
进行重新分配,并在将其指定给原始指针之前检查返回值