gpt4 book ai didi

c - 您将如何动态地将字符添加到数组中?没有预定义数组?

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

如果我想将字符添加到字符数组,我必须这样做:

#include <stdio.h>

int main() {
int i;
char characters[7] = "0000000";
for (i = 0; i < 7; i++) {
characters[i] = (char)('a' + i);
if (i > 2) {
break;
}
}

for (i = 0; i < 7; i++) {
printf("%c\n", characters[i]);
}
return 0;
}

为了防止打印任何奇怪的字符,我必须初始化数组,但它不灵活。如何动态地将字符添加到 char 数组?就像在 Python 中一样:

characters = []
characters.append(1)
...

最佳答案

纯 C 没有非丑陋的解决方案。

#include <stdio.h>

int main() {
int i;
size_t space = 1; // initial room for string
char* characters = malloc(space); // allocate
for (i = 0; i < 7; i++) {
characters[i] = (char)('a' + i);
space++; // increment needed space by 1
characters = realloc(characters, space); // allocate new space
if (i > 2) {
break;
}
}

for (i = 0; i < 7; i++) {
printf("%c\n", characters[i]);
}
return 0;
}

在实践中,您希望避免使用 realloc 并且当然会以比一个字节更大的 block 分配内存,甚至可能以指数速率分配内存。但本质上,这就是 std::string 等的幕后发生的事情:你需要一个计数器,它计算当前大小,一个当前最大大小的变量(为简单起见,这里它总是当前大小+1)和如果空间需求超过当前最大大小,则进行一些重新分配。

关于c - 您将如何动态地将字符添加到数组中?没有预定义数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5905379/

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