gpt4 book ai didi

c - 分配一个未知大小的数组

转载 作者:太空宇宙 更新时间:2023-11-03 23:55:06 24 4
gpt4 key购买 nike

上下文:我想做的是制作一个程序,它将文本作为输入并将其存储在字符数组中。然后我将数组的每个元素打印为小数。例如。 “Hello World”将被转换为 72、101 等。我会将其用作快速 ASCII2DEC 转换器。我知道有在线转换器,但我想自己制作一个。

问题:如何分配一个在编译时大小未知的数组,并使其与我输入的文本大小完全相同?因此,当我输入“Hello World”时,它会动态生成一个数组,其大小恰好只需要存储“Hello World”。我在网上搜索过,但找不到任何我可以使用的东西。

最佳答案

我看到您使用的是 C。您可以这样做:

 #define INC_SIZE 10

char *buf = (char*) malloc(INC_SIZE),*temp;
int size = INC_SIZE,len = 0;
char c;

while ((c = getchar()) != '\n') { // I assume you want to read a line of input
if (len == size) {
size += INC_SIZE;
temp = (char*) realloc(buf,size);
if (temp == NULL) {
// not enough memory probably, handle it yourself
}
buf = temp;
}
buf[len++] = c;
}
// done, note that the character array has no '\0' terminator and the length is represented by `len` variable

关于c - 分配一个未知大小的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9963026/

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