C - 由变量定义的长度的静态数组

Hap*_*ave 1 c arrays variables initialization

我实际上正在使用C语言进行分配,为了实现我的需要,我需要使用一个静态数组,让我们说

static int array[LEN];
Run Code Online (Sandbox Code Playgroud)

诀窍是这个数组长度LEN是在main().例如

static int LEN;

void initLen(int len) {
LEN = len;
}

static int array[LEN];
Run Code Online (Sandbox Code Playgroud)

在哪里initLen调用main,并len使用用户给出的参数计算.

这个设计的问题是我得到了错误

threadpool.c:84: error: variably modified ‘isdone’ at file scope
Run Code Online (Sandbox Code Playgroud)

该错误是由于我们无法使用变量作为长度初始化静态数组.为了使它工作,我正在定义LEN_MAX和写

#define LEN_MAX 2400

static int array[LEN_MAX]
Run Code Online (Sandbox Code Playgroud)

这个设计的问题是我暴露自己的缓冲区溢出和segfaults :(

所以我想知道是否有一些优雅的方法来初始化具有确切长度的静态数组LEN

先感谢您!

K S*_*iel 6

static int LEN;
static int* array = NULL;

int main( int argc, char** argv )
{
    LEN = someComputedValue;
    array = malloc( sizeof( int ) * LEN );
    memset( array, 0, sizeof( int ) * LEN );
    // You can do the above two lines of code in one shot with calloc()
    // array = calloc(LEN, sizeof(int));
    if (array == NULL)
    {
       printf("Memory error!\n");
       return -1;
    }
    ....
    // When you're done, free() the memory to avoid memory leaks
    free(array);
    array = NULL;
Run Code Online (Sandbox Code Playgroud)