2013-04-08 79 views
1

實際上,我工作的C中的assignement,併爲需要我的實現,我需要使用一個靜態數組定義的長度,讓我們說Ç - 靜態數組由一個變量

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靜態數組一些優雅的方式?

預先感謝您!

+0

什麼是'isdone',它與你的數組有什麼關係?在你的問題中,除了錯誤消息之外,沒有提到這個'isdone'變量。請提供[SSCCE](http://sscce.org/)。 – 2013-04-08 15:13:36

+0

@JoachimPileborg well'isdone'只是我的程序中的真正數組,在我的例子中我只是簡單地調用'array'。 – HappyRave 2013-04-08 15:55:17

回答

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; 
+0

這真是太棒了! :D 不知道爲什麼我沒有想到指針! 謝謝! – HappyRave 2013-04-08 15:14:27

+0

沒有人期待西班牙宗教裁判所,呃,我的意思是指針! – 2013-04-08 15:40:34

+0

如果'malloc'失敗,我認爲你應該返回一個錯誤狀態。 – effeffe 2013-04-08 16:49:51

1

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

現在不要忘記在使用它之前先初始化數組。