2017-06-18 63 views
-8
*#include <iostream> 
using namespace std; 
class Tree{ 
    static int height[0]; 
public: 
    static int countBalanceTree(int h){  
     height[0]=height[1]=1; 
     for(int i=2;i<=h;i++){ 
      height[i]=height[i-1]*(height[i-1]+2*height[i-2]); 
     } 
     return height[h]; 
    } 
}; 
int Tree::height[]; 
int main(void){ 
    int h; 
    cout<<"Enter height = "; 
    cin>>h; 
    cout<<(Tree::countBalanceTree(h))<<" Balanced Tree can be create of height "<<h<<endl; 
    return 0; 
}* 

如果我將輸入h作爲任何東西(例如3),它仍然可以工作並打印輸出,但數組大小爲零。這個C++代碼如何工作?

+2

問誰寫的?使用調試器來完成它? – Borgleader

+2

你只是有一個直接的緩衝區溢出破壞內存... – VTT

回答

1

數組不靈活,其大小在編譯時是固定的。如果你超出範圍(做一個零大小的陣列),你將有未定義的行爲

如果您想要一個「陣列」,您可以設置或更改run-rime的大小,然後使用std::vector

+0

但數組大小爲零,所以這應該在運行時失敗,但它的運行和打印輸出。怎麼樣? –

+0

@kamleshsolanki不幸的是,未定義行爲的可能性之一似乎很好。 –

+0

C語言在運行時不會檢查數組邊界。這會使C語言效率降低。 –