2011-09-05 94 views
7
if(stat("seek.pc.db", &files) ==0) 
    sizes=files.st_size; 

sizes=sizes/sizeof(int); 
int s[sizes]; 

我編譯這在Visual Studio 2008和我得到以下錯誤: 錯誤C2057:預期常量表達式 錯誤C2466:不能分配恆定大小爲0錯誤C2057:預期常量表達式

的陣列

我試過使用矢量s [尺寸]但無濟於事。我究竟做錯了什麼?

謝謝!

+1

只是想通知它一個依賴於編譯器的問題,用gcc(C99)試一試,你的代碼將被編譯。 –

回答

9

C中數組變量的大小在編譯時必須已知。如果你只是在運行時才知道它,你將不得不malloc而不是你自己。

+3

C99確實有可變長度數組(VLA),但是Microsoft的編譯器不支持它們。 ('不能分配一個常量大小爲0的數組錯誤可能只是編譯器被混淆了。) –

+0

我試圖通過int * s = new int [sizes];來分配內存。它給我System.AccessViolationException錯誤。是因爲這個嗎? – Ava

+0

@Richa,聽起來更像是.net而不是C。而'new int [size]'不是C語法,而是C++。 –

4

數組的大小必須是編譯時間常量。但是,C99支持可變長度數組。因此,而不是你的代碼在你的環境中工作,如果數組的大小在運行時則稱爲 -

int *s = malloc(sizes); 
// .... 
free s; 

關於錯誤消息:

int a[5]; 
    //^5 is a constant expression 

int b = 10; 
int aa[b]; 
    //^ b is a variable. So, it's value can differ at some other point. 

const int size = 5; 
int aaa[size]; // size is constant. 
+0

我可以初始化size爲'const int size = 5;'中的變量嗎? – Ava

+0

@Richa - 你必須初始化一個常量變量。您無法對其執行任何類型的分配。 http://ideone.com/D4L5r – Mahesh

+0

我試圖通過'int * s = new int [sizes];'來分配內存。它給我System.AccessViolationException錯誤。是因爲這個嗎? – Ava