如果我想将char添加到char数组,我必须这样做:
#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;
}
Run Code Online (Sandbox Code Playgroud)
为了防止打印任何奇怪的字符,我必须初始化数组,但它不灵活.如何动态地将字符添加到char数组?就像你在Python中一样:
characters = []
characters.append(1)
...
Run Code Online (Sandbox Code Playgroud)
    Gun*_*iez 10
纯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;
}
Run Code Online (Sandbox Code Playgroud)
在实践中,您希望避免使用realloc,当然还要将内存分配给更大的块而不仅仅是一个字节,甚至可能以指数速率分配.但实质上这就是在std :: string等引擎下发生的事情:你需要一个计数器,它计算当前大小,当前最大大小的变量(为简单起见,它总是当前大小+ 1)和如果对空间的需求超过最大当前大小,则进行一些重新分配.