#include <stdio.h>
#include <stdlib.h>
int main(int argc, char* argv[]){
char buffer[103];
char **words = malloc(1 * sizeof(*words));
size_t counter = 0;
size_t array_size = 2;
for(int i = 0; i < 5; i++){
if(!fgets(buffer, 103, stdin)){
fputs("fgets failed", stderr);
}
words[counter] = buffer;
char **more_words = realloc(words, array_size * sizeof(*more_words));
words = more_words;
array_size++;
counter ++;
}
printf("********************************************************");
for(int i = 0; i < 5; i++){
printf("%s\n", words[i]);
}
}
现在这是我正在处理的简化代码。 我知道我不会处理很多可能发生的错误。
要点是,当您执行此操作时,单词数组似乎有 5 个“最后”条目。
假设你给 fgets :
1
2
3
4
5
然后
words[0] = 5;
words[1] = 5;
words[2] = 5;
words[3] = 5;
words[4] = 5;
为什么不是:
words[0] = 1;
words[1] = 2;
words[2] = 3;
words[3] = 4;
words[4] = 5;
?
最佳答案
问题不在于realloc
,而在于您分配给您分配的指针的内容:
words[counter] = buffer;
buffer
始终是同一个指针,因此您最终会读取到缓冲区中的最后一个字符串。
您需要malloc
并为每一行复制缓冲区:
words[counter] = malloc(strlen(buffer)+1);
strcpy(words[counter], buffer);
不用说,您应该是 NULL
- 在将 realloc
返回的值赋回给 words
之前检查它。
关于C: Realloc 的行为方式我不明白为什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36952663/