我在C中有一个问答游戏,当用户输入错误答案和对该问题的相应正确答案时,我使用一种结构保存该结构。首先,我使用malloc为单个结构分配了内存。
Struct:
typedef struct
{
char* wrongAnswers;
char* corrections;
} Corrections;
Malloc:
Corrections* corrections = (Corrections*)malloc(sizeof(Corrections));
稍后,在我的程序中,我具有以下功能:错误答案会增加一个'incorrectAnswers'变量,该变量用于重新分配内存以允许存储新的错误答案及其相应的正确答案。
代码:
// Extract characters from file and store in character c
for (c = getc(fPointerOpen); c != EOF; c = getc(fPointerOpen)) {
if (c == '\n') // Increment count if this character is newline
numberOfLines++;
}
for (int i = 0; i < numberOfLines; i++) {
int lengthOfQuestion = 150;
if (v == 0) {
printf("Correct\n");
score++;
}
else {
printf("Incorrect\n");
incorrectAnswers++;
corrections = (Corrections*)realloc(corrections, incorrectAnswers * sizeof(Corrections));
corrections[i].wrongAnswers = malloc(sizeof(char) * lengthofanswer);
corrections[i].wrongAnswers = lines[i].userAnswers;
corrections[i].corrections = malloc(sizeof(char) * lengthofanswer);
corrections[i].corrections = lines[i].answers;
}
printf("Your score is %d/%d\n", score, (i + 1));
}
我收到的错误取决于输入正确答案和错误答案的顺序。我尝试在程序的不同部分中使用free(),并且我注意到当我输入错误的答案作为程序的最后一个条目时,该错误将始终出现/如果输入的是正确的然后是错误的答案。为什么会这样呢?我的理解是我错误地实现了重新分配。
您应使用strcpy
复制字符串,请勿使用=
在c中分配字符串。
strcpy(corrections[i].wrongAnswers,lines[i].userAnswers);
strcpy(corrections[i].corrections,lines[i].answers);
每次使用malloc
或realloc
时,应检查这些函数的返回值。