我需要一个字符串数组,其中在编译时不知道数组的长度。我所做的是:动态调整字符串数组的大小
char **words;
words = malloc(capacity * sizeof(char *));
char nextword[MAX_LEN + 1];
while (true) {
if (num_entries == capacity) {
capacity += 5;
realloc(words, (sizeof(char *) * capacity));
}
printf("\nEnter a word: ");
fgets (nextword, MAX_LEN, stdin);
remove_newline(nextword);
if (strlen(nextword) == 0) break;
words[num_entries] = malloc(strlen(nextword + 1));
if (words[num_entries] == NULL) {
printf("\nout of space\n");
break;
}
strcpy(words[num_entries], nextword);
num_entries++;
这似乎工作,一旦扩大规模,但扩容后的第一个元素已经成为NULL
出于某种原因。第二次realloc
执行我得到一个错误:
"invalid next size"
.
感谢您的链接。它非常有帮助。 – Wcrousse
链接很好,但是在计算器中,如果链接不再工作,则需要直接在此处显示解决方案。 –
@YohanObadia代码不是必需的,只要解释足以找出问题所在。解决方法是通过解释问题所在(我的意思是“realloc不会修改您传递给它的值”部分)。 – dasblinkenlight