gpt4 book ai didi

c - 在不知道大小的情况下输入字符串

转载 作者:太空狗 更新时间:2023-10-29 16:10:24 25 4
gpt4 key购买 nike

当我想存储我不知道大小的字符串时,该怎么办。

我喜欢这样:

#include <stdio.h>    
#include <conio.h>

int main () {
char * str;
str = (char *)malloc(sizeof(char) + 1);
str[1] = '\0';
int i = 0;
int c = '\0';

do {
c = getche();
if(c != '\r'){
str[i] = c;
str[i + 1] = '\0';
i++;
str = (char *)realloc(str, sizeof(char) + i + 2);
}
} while(c != '\r');

printf("\n%s\n", str);

free(str);
return 0;
}

我找到这个页面: Dynamically prompt for string without knowing string size

是否正确?如果是,则:

有没有更好的方法?

有没有更高效的方法?

最佳答案

Is it correct?

没有

主要问题是realloc的使用。这是错误的。使用 realloc 时,永远不要直接分配给指向已分配内存的指针 - 始终使用临时变量来获取返回值。喜欢:

char * temp;
temp = realloc(str, 1 + i + 2);
if (temp == NULL)
{
// out of memory
.. add error handling
}
str = temp;

原因是 realloc 可能会失败,在这种情况下它会返回 NULL。因此,如果您直接分配给 strrealloc 失败,则您丢失了指向已分配内存(又名字符串)的指针。

除此之外:

1) 不要强制转换 mallocrealloc

2) sizeof(char) 总是 1 - 所以你不需要使用它 - 只需输入 1

Is there any better way? Is there more efficient way?

与其在每个循环中重新分配 1 - 这在性能方面相当昂贵 - 在许多情况下(重新)分配更大的 block 更好。

一种策略是每当调用realloc 时将分配加倍。因此,如果您分配了 128 个字节,那么下一个分配应该是 2*128=256。另一种策略是让它以某个明显大于 1 的固定大小增长 - 例如,您可以让它每次增长 1024。

关于c - 在不知道大小的情况下输入字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46706111/

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