1

我有大约 12000 个预先知道的值,我需要在程序的早期将它们放入一个数组中。在某些情况下,我稍后需要使用 realloc 调整这个数组的大小。有没有办法用 malloc/calloc 初始化一个数组,或者用其他几个值填充一个数组?

4

2 回答 2

4

You cannot initialize a malloced array this way, your best chance is to have it statically in your program, and copy it to a malloced array at the beginning of the run, e.g.:

static int arr[] = {1,2,3,4};
static int * malloced_arr;

// in the init function
malloced_arr = malloc(sizeof(arr));
if (malloced_arr)
{
    memcpy(malloced_arr, arr, sizeof(arr));
}
于 2012-05-16T04:26:43.070 回答
1

这就是零长度数组有用的东西。例如:

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

struct values {
    int x[4];
    int y[0];
} V = { {1, 2, 3} };

int
main( int argc, char ** argv )
{
    int *t;
    int i;
    struct values *Y;

    (void) argc; (void) argv;
    /* Allocate space for 100 more items */
    Y = malloc( sizeof *Y + 100 * sizeof *Y->y );
    t = Y->x;
    memcpy( Y, &V, sizeof V );
    t[3] = 4;

    for( i = 0; i < 4; i++ )
        printf( "%d: %d\n", i, t[ i ]);

    return 0;
}

当然,这实际上只是一个客厅技巧,对 Binyamin 的解决方案没有任何好处,并且引入了许多完全不必要的混淆。

于 2012-05-16T04:36:11.930 回答