2014-04-12 20 views
0

我有以下功能:數組在C++中有函數的垃圾值!

int *array1=new int [3]; 
    void My_function() 
    { 
    My_set(array1); 
    for(int i=0;i<3;i++){ //The output is 5 15 55 
    cout<<array1[i]<<endl; 
    } 
    Display (array1) 

    } 

    void My_set(int *array1) 
    { 
    array1[0]=5; 
    array1[1]=15; 
    array1[2]=55; 
    } 

    void Display(int *array1){ 
    for(int i=0;i<3;i++){ 
    cout<<array1[i]<<endl; //The output is Garbage -842150451 
    } 

    } 

注:發生在複雜的項目這個問題,但我告訴我的問題,簡單的代碼! 謝謝:)

+0

對我的作品的http://ideone.com/GBkVTo ... – yizzlez

+0

使用'標準::矢量',它會提醒你當你在大多數調試編譯器中溢出緩衝區時。 –

+0

@awesomeyi:你編譯的代碼有未定義的行爲。因此,它做到了你所期望的事情並不重要。 –

回答

1

您需要聲明您的數組像這樣int *array1 = new int[3];

+0

甚至沒有使用新的,因爲它從來沒有變化的大小.. – Dan

+0

當然,我想知道他/她爲什麼用新的聲明。圖爲測試?但丹提出了一個很好的觀點。 @ user3316887如果最終以動態大小創建數組,請確保將數組大小作爲參數傳遞給函數。 – Inertiatic