C – 由变量定义的长度的静态数组
我实际上正在使用C语言进行分配,为了实现我的需要,我需要使用一个静态数组,让我们说
static int array[LEN];
诀窍是这个数组长度LEN
是在main()
计算的。 例如
static int LEN; void initLen(int len) { LEN = len; } static int array[LEN];
在initLen
中调用initLen
,并使用用户给出的参数计算len
。
这个设计的问题是我得到了错误
threadpool.c:84: error: variably modified 'isdone' at file scope
该错误是由于我们无法使用变量作为长度初始化静态数组。 为了使它工作,我正在定义一个LEN_MAX
并写
#define LEN_MAX 2400 static int array[LEN_MAX]
这个设计的问题是我暴露自己的缓冲区溢出和segfaults 🙁
所以我想知道是否有一些优雅的方法来初始化一个具有确切长度LEN
的静态数组?
先感谢您!
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;
我建议使用malloc
:
static int *array; void initArray(int len) { if ((array = malloc(sizeof(int)*len)) != NULL) { printf("Allocated %d bytes of memory\n", sizeof(int)*len); } else { printf("Memory error! Could not allocate the %d bytes requested!\n", sizeof(int)*len); } }
现在不要忘记在使用之前初始化数组。