Ç - 长度静态数组由一个变量定义 [英] C - Static Array with length defined by a variable

查看:141
本文介绍了Ç - 长度静态数组由一个变量定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

实际上,我工作的C中的assignement,并为需要我的实现,我需要使用一个静态数组,假设

 静态int数组[LEN]

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

 静态INT LEN;无效initLen(INT LEN){
LEN = LEN;
}静态int数组[LEN]

其中, initLen 是所谓的 LEN 使用由用户给定的参数来计算。

这种设计的问题,是我的错误。

  threadpool.c:84:错误:在文件范围内动态可变'isdone

该错误是由于这样的事实,我们不能用初始化变量长度静态数组。为了使它工作,我定义一个 LEN_MAX

 的#define LEN_MAX 2400静态int数组[LEN_MAX]

这种设计的问题是,我自己暴露为缓冲区溢出和设计缺陷:(

所以我想知道如果有初始化与精确长度的静态数组一些优雅的方式 LEN

感谢你在前进!


解决方案

 静态INT LEN;
静态INT *阵列= NULL;INT主(INT ARGC,字符** argv的)
{
    LEN = someComputedValue;
    阵列=的malloc(sizeof的(INT)* LEN);
    memset的(数组,0,sizeof的(INT)* LEN);
    //你可以做code以上两行一杆用calloc()
    //阵列=释放calloc(LEN,sizeof的(INT));
    如果(阵列== NULL)
    {
       的printf(内存错误。\\ n!);
       返回-1;
    }
    ....
    //当你完成后,免费的(),以避免内存泄漏内存
    免费(数组);
    阵= NULL;

I'm actually working on an assignement in C, and for the need of my implementation, I need to use a static array, let's say

static int array[LEN];

The trick is that this array length, LEN, is computed in the main(). For example

static int LEN;

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

static int array[LEN];

Where initLen is called in the main, and len is computed using the arguments given by the user.

The issue with this design, is that I get the error

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

The error is due to the fact that we cannot initialize static arrays using variables as length. To make it work, I'm defining a LEN_MAX and write

#define LEN_MAX 2400

static int array[LEN_MAX]

The issue with this design is that i'm exposing myself for buffers overflows and segfaults :(

So I'm wondering if there is some elegant way to initialize a static array with the exact length LEN?

Thank you in advance!

解决方案

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;

这篇关于Ç - 长度静态数组由一个变量定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆