如何声明任意大小的数组

Nu *_*Mik 4 c arrays size malloc

好吧,这是一道C编程作业题。但我真的被困住了。

我要求用户输入单词,然后将输入插入到数组中,但我无法控制用户输入的单词数量。

我想我要问的是如何在 C 中声明一个数组而不声明其长度,也不询问用户长度应该是多少。

我知道这与 malloc 有关,但如果您能给我一些如何执行此操作的示例,我将非常感激。

pax*_*blo 5

您可以使用malloc足够大的内存块来容纳一定数量的数组项。

然后,在超过该数字之前,您可以使用realloc更大的内存块。

下面的一段 C 代码展示了这一点,当整数数组太小而无法容纳下一个整数时,就会重新分配该数组。

#include <stdio.h>
#include <stdlib.h>

int main (void) {
    int *xyzzy = NULL;   // Initially NULL so first realloc is a malloc.
    int currsz = 0;      // Current capacity.
    int i;

    // Add ten integers.

    for (i = 0; i < 10; i++) {
        // If this one will exceed capacity.

        if (i >= currsz) {
            // Increase capacity by four and re-allocate.

            currsz += 4;
            xyzzy = realloc (xyzzy, sizeof(int) * currsz);
                // Should really check for failure here.
        }

        // Store number.

        xyzzy[i] = 100 + i;
    }

    // Output capacity and values.

    printf ("CurrSz = %d, values =", currsz);
    for (i = 0; i < 10; i++) {
        printf (" %d", xyzzy[i]);
    }
    printf ("\n");

    return 0;
}
Run Code Online (Sandbox Code Playgroud)