[英]How do I call my function that returns an array of pointers? C++
指針完全陌生,因此對於新手問題深表歉意。 嘗試調用函數時收到轉換錯誤。 該函數應該返回一個指向最后包含1的更新數組的指針。
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的轉換錯誤,但是我不確定為什么嗎? 函數參數必須保持原樣。
謝謝您的幫助。
我在您的代碼中發現一個錯誤。
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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.