【问题标题】:C - Static Array with length defined by a variableC - 长度由变量定义的静态数组
【发布时间】:2013-04-08 15:08:50
【问题描述】:

我实际上是在用 C 进行赋值,为了实现我的需要,我需要使用一个静态数组,比如说

static int array[LEN];

诀窍在于这个数组长度LEN 是在main() 中计算的。例如

static int LEN;

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

static int array[LEN];

其中initLen 在main 中被调用,len 是使用用户提供的参数计算的。

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

threadpool.c:84: error: variably modified ‘isdone’ at file scope

错误是由于我们无法使用变量作为长度来初始化静态数组。为了让它工作,我定义了一个LEN_MAX 并写了

#define LEN_MAX 2400

static int array[LEN_MAX]

这种设计的问题是我将自己暴露在缓冲区溢出和段错误中:(

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

提前谢谢你!

【问题讨论】:

  • 什么是isdone,它与您的阵列有什么关系?除了错误消息之外,您的问题中没有提到这个 isdone 变量。请改为提供SSCCE。

标签: c arrays variables initialization


【解决方案1】:
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;

【讨论】:

    【解决方案2】:

    我建议使用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);
       }
    }
    

    现在不要忘记初始化数组,然后才能使用它。

    【讨论】:

      猜你喜欢
      • 2017-11-15
      • 2011-08-17
      • 2012-05-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-29
      • 1970-01-01
      • 2012-08-25
      相关资源
      最近更新 更多