2017-02-12 42 views
0

完全新指針,所以我對新手的問題表示歉意。嘗試調用我的函數時收到轉換錯誤。 這個函數應該返回一個指向最後包含1的更新數組的指針。如何調用返回指針數組的函數? C++

int* appendList(int x, int &arraySize, int *list) 
{ 
    arraySize++; 
    int *array2 = new int[arraySize]; 
    for(int i=0; i < arraySize-1; i++) 
    { 
     array2[i] = list[i-1]; 
    } 
    array2[arraySize]=x; 

    return array2; 
} 

我的主要功能如下。

int main() 
{ 
    int size=0; 
    int *list; 
    cout << "Please enter the size of your array: "; 
    cin >> size; 
    list = new int[size]; 
    cout << "\nPlease enter the numbers in your list seperated by spaces: "; 
    for(int i=0; i < size; i++) 
    { 
     cin >> list[i]; 
    } 
    cout << endl; 
    cout << "The array you entered is listed below\n "; 
    for(int i=0; i < size; i++) 
    { 
     cout << setw(3) << list[i]; 
    } 

    list = appendList(1, size, list); 
    for(int i=0; i < size; i++) 
    { 
     cout << setw(3) << list[i]; 
    } 

    return 0; 
} 

函數appendList的調用導致參數3的轉換錯誤,但我不知道爲什麼?函數參數必須保持原樣。

謝謝你的幫助。

+1

您使用'cout'和'setw'而不使用'std ::',所以我想你在上面聲明瞭'using namespace std'。然後'list'變量名可能與'std :: list '發生衝突。嘗試使用其他名稱。 –

+0

我可以使用其他什麼名字? –

+0

list1,my_list,ary或與C++關鍵字或STL模板不同的名稱。或者您可以嘗試不使用'使用名稱空間標準;'來公開std ::中的所有名稱。 –

回答

2

我在代碼中發現了一個錯誤。

int* appendList(int x,int &arraySize,int *list) 
     { 
     arraySize++; 
     int *array2=new int[arraySize]; 
     for(int i=0;i<arraySize-1;i++) 
     { 
      array2[i]=list[i-1];//this is incorrect because for i=0 it becomes list[-1] which is wrong 
     } 
     array2[arraySize]=x; 

     return array2; 
     } 
+1

謝謝,我甚至沒有能夠調試它,因爲我無法正確調用函數。 –