2012-02-23 39 views
4

我最近提交了一個小程序,分配是有以下兩個功能和它內部的一個主要方法中:C:的內存狀態的數組聲明

/** 
    * Counts the number of bits it 
    * takes to represent an integer a 
    */ 
    int num_bits(int a) 
    { 
     int bitCount = 0; 

     while(a > 0) 
     { 
     bitCount++; 
     a = a >> 1; //shift to the right 1 bit 
     } 

     return bitCount; 
    } 

    /** 
    * Converts an integer into binary representation 
    * stored in an array 
    */ 
    void int2bin_array(int a, int *b) 
    { 
     //stopping point in search for bits 
     int upper_bound = num_bits(a); 

     int i; 
     for(i = 0; i < upper_bound; i++) 
     { 
     *(b+i) = (a >> i) & 1; //store the ith bit in b[i] 
     } 
    } 

int main() 
{ 
    int numBits = num_bits(exponent); 
    int arr[numBits];  //<- QUESTION IS ABOUT THIS LINE 
    int2bin_array(exponent, arr); 

    //do some operations on array arr 
} 

當我的教練回來,他編寫的程序關於我上面標說,由於numBits值不知道,直到運行時,初始化數組的大小numBits是一個危險的操作,因爲編譯器將不知道多少內存分配給數組arr該行的註釋。

我在想,如果有人能:

1)確認,這是一個危險的操作

2)解釋什麼是內存明智的打算時,我初始化這樣一個數組,編譯器如何知道什麼內存分配?有什麼辦法可以確定分配了多少內存?

任何輸入將不勝感激。

+0

http://en.wikipedia.org/wiki/Variable-length_array – Mysticial 2012-02-23 02:33:51

回答

2

這是一個C99可變長度的數組。它在運行時在棧上分配的(不是由編譯器),並且基本上等同於

char *arr = alloca(num_bits); 

在這種情況下,因爲你可以知道上限的功能,它是比較小的,你」 d是最好關閉與

char arr[sizeof(int)*CHAR_BIT]; 

這個數組在編譯時已知的大小,總是會適合你需要的一切,並在平臺上工作沒有C99支持。

+0

感謝您的回覆。當我用gcc進行編譯時,我沒有設置'-std = c99',但是這個代碼運行的很好,在這種情況下,我只是很幸運,因爲upper_bound很低? – 2012-02-23 02:45:41

+0

gcc默認包含一堆非標準的C擴展。 'gcc -std = c89 -pedantic'不會編譯你的代碼。 – Dave 2012-02-23 02:46:43

+0

謝謝,這正是我正在尋找的。 – 2012-02-23 02:49:02

2

應該差不多,它只是進入堆疊。
唯一的危險是吹出堆棧。

的malloc會以正常的方式,那麼你還是知道,如果你有足夠的內存不是也對下一步做什麼做出明智的決定。但在很多情況下,可以假設你可以在堆棧上放置不太大的物體。

但嚴格來說,如果你沒有足夠的空間,這將嚴重失敗。

+0

感謝您的答覆。 – 2012-02-23 02:46:07