2013-05-02 56 views
-1

我想打一個隨機大小的數組每次程序執行在第一,但編譯罵我開頭的隨機數組大小?

"Error 2 error C2466: cannot allocate an array of constant size 0" 

有什麼辦法,我可以隨意選擇SIZE通過SIZE = rand() % 100開頭,然後用int myarray[SIZE]={0} intialize的陣列? ??或者我應該每次在開始時用一個確切的數字初始化它?

int main(void) { 
    int i; 
    int SIZE=rand()%100; 
    int array2[SIZE]={0}; 

    for(i=0;i<SIZE;i++)  //fill the array with random numbers 
     array2[i]=rand()%100; 
    ... 
} 
+5

當然,使用malloc。 – Mike 2013-05-02 18:00:35

+1

您需要一個編譯器,該編譯器在一個標準中沒有被卡住,同時被替換兩次。在C99中添加了VLA(但不能初始化VLA,如'int array2 [SIZE] = {0}')。 – 2013-05-02 18:01:35

+1

堆棧上變量的分配要求知道大小。如果您希望動態調整大小,請使用堆('malloc()')。 – 2013-05-02 18:02:56

回答

1

您可以使用malloc()calloc()做這在C例如,

int SIZE=(rand()%100)+1; // size can be in the range [1 to 100] 
int *array2 = (int*) malloc(sizeof(int)*SIZE); 

但在同一時間,陣列尺寸不能大於恆定值的任何其他。

以下兩個聲明是有效的。

int a[10]; 

#define MAX 10 
int b[MAX]; 

但是,如果你嘗試使用下面的方法來聲明,你會得到一個錯誤。

int x=10; 
int a[x]; 

const int y=10; 
int b[y]; 
+0

非常感謝這工作 – Lyrk 2013-05-02 18:19:31

+0

此解決方案的一個注意事項:[在C中,不要從malloc返回類型轉換](http:// stackoverflow。com/questions/605845/do-i-cast-of-malloc/605858#605858) – Mike 2013-05-02 18:24:16

1

注意rand()%100能夠而且將會0。如果你想有一個隨機值1 < = N < = 100,那麼你需要使用(rand()%100)+1

1

要做到這一點是使你的數組​​的指針,並使用malloc的最佳方式:

int SIZE=(rand()%100) + 1; //range 1 - 100 
int *array2 = malloc(sizeof(int) * SIZE); 

之後,您可以使用array2多少,你會使用數組。

+0

int * array2 =(int *)malloc(sizeof(int)* SIZE);工程 – Lyrk 2013-05-02 18:20:04

+0

此解決方案的一個注意事項:[在C中,不要從malloc返回類型轉換](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc/605858# 605858) – Mike 2013-05-02 18:24:42

+0

@Mike,嗯,很高興知道。我來自C++背景。 – ApproachingDarknessFish 2013-05-02 18:26:03

2

您表示您使用的是Microsoft的visual studio。 MS的視覺工作室是而不是 c99 compilant(他們櫻桃挑選最好)和缺少的功能之一是VLAs

最好的,你就可以使用MS VS做的就是這樣做動態使用malloc()

int main(int argc, char *argv[]) 
{ 
    int i; 
    int SIZE=rand()%100; 
    int *array2=malloc(SIZE * sizeof(int)); // allocate space for SIZE ints 

    for(i=0;i<SIZE;i++)  //fill the array with random numbers 
     array2[i]=rand()%100; 
    free(array2); // free that memory when you're done. 
    return 0; 
} 

如果要切換編譯器,還有其他的選擇。