gpt4 book ai didi

c - realloc 后数据被覆盖

转载 作者:太空宇宙 更新时间:2023-11-04 07:11:56 26 4
gpt4 key购买 nike

I 一个允许您向游戏添加问题的功能。我使用 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;
}
}

当我添加新问题时,旧问题会被覆盖。图片:当我毫无问题地添加第一个问题时 First image where everything works

图片:当我添加更多问题时,我遇到了问题。 Second image where it fails

最佳答案

您的代码不会尝试保留之前的问题。它总是使用 NULL 指针调用 realloc(),从而产生全新的分配:

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

(为清楚起见,我没有包括任何错误检查。您可能需要添加一些。)

关于c - realloc 后数据被覆盖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27720397/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com