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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5905379/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 08:34:59  来源:igfitidea点击:

How would you add chars to an array dynamically? Without the array being predefined?

carrayschar

提问by Vayn

If I want to add chars to char array, I must do it like this:

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

#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;
}

To prevent from printing any weird characters, I must initialize the array, but it isn't flexible. How can I add characters to a char array dynamically? Just like you would in Python:

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

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

回答by Gunther Piez

There is no non-ugly solution for pure C.

纯 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;
}

In practice you want to avoid the use of realloc and of course allocate the memory in bigger chunks than just one byte, maybe even at an exponetial rate. But in essence thats what happening under the hood of std::string and the like: You need a counter, which counts the current size, a variable of the current maximum size (Here it is always current size+1, for simplicity) and some reallocation if the need for space surpasses the maximum current size.

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

回答by Pete Wilson

Yes, of course you can add characters dynamically:

是的,当然您可以动态添加字符:

quote char[100] = "The course of true love";
      strcat( quote, " never did run smooth.";

but only if there is enough room in quote[ ] to hold the appended characters. Or maybe you are asking why, in C, you have to pre-arrange enough character storage whereas, in Python, storage is allocated dynamically. That's how the language was designed in 197x.

但前提是 quote[ ] 中有足够的空间来容纳附加的字符。或者您可能会问,为什么在 C 中必须预先安排足够的字符存储,而在 Python 中,存储是动态分配的。这就是该语言在 197x 中的设计方式。

C99doesallow dynamically-allocated storage: storage allocated by the system at run time. And a very bad mistake it is, imo.

C99确实允许动态分配存储:系统在运行时分配的存储。这是一个非常严重的错误,imo。

回答by Dhaivat Pandya

You cannot unless you use Linked Listsor some other custom data structure.

除非您使用链表或其他一些自定义数据结构,否则您不能。