[英]Print contents of array modified in function
在我的main()
函數中,我聲明了一個int
類型的array
,數字為 1 到 10。然后我還有另外兩個int*
類型的函數,它們以這個數組及其大小作為參數,執行一些操作,每個函數都返回一個指針到新數組。 我遇到問題的地方是打印數組內容的第三個函數。
#include <iostream>
using namespace std;
const int SIZE_OF_ARRAY = 10;
int main() {
int array[SIZE_OF_ARRAY] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int *ptr1 = 0;
ptr1 = function1(array, SIZE_OF_ARRAY);
print(array, SIZE_OF_ARRAY);
cout << endl;
int *ptr2 = 0;
ptr2 = function2(array, SIZE_OF_ARRAY);
print(array, SIZE_OF_ARRAY);
return 0;
}
void print(int array[], const int SIZE_OF_ARRAY)
{
for (int i = 0; i < (SIZE_OF_ARRAY * 2); i++)
{
cout << array[i] << " ";
}
}
int* function1(int array[], const int SIZE_OF_ARRAY)
{
int *ptr = new int[SIZE_OF_ARRAY];
// Do stuff.
return ptr;
}
int* function2(int array[], const int SIZE_OF_ARRAY)
{
int *ptr2 = new int[SIZE_OF_ARRAY * 2];
// Create new array double in size, and set contents of ptr2
// to the contents of array. Then initialize the rest to 0.
return ptr2;
}
正如這里預期的那樣,兩次調用print()
函數的結果類似於:
1 2 3 4 5 6 7 8 9 10 465738691 -989855001 1483324368 32767 -1944382035 32767 0 0 1 0
1 2 3 4 5 6 7 8 9 10 465738691 -989855001 1483324368 32767 -1944382035 32767 0 0 1 0
但我希望結果是這樣的:
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10 0 0 0 0 0 0 0 0 0 0
我怎樣才能做到這一點? (請注意,對於此作業,我使用的是 C++98)。 提前致謝。
new int[SIZE_OF_ARRAY]
分配內存,但不為數組元素賦值。 您看到的是為數組分配內存時該內存中的內容。 您可以更改您的function2
以將零分配給數組元素,如果這是您想要的。
首先,要打印不同數量的兩個調用元素來print
,所以你不應該委托決定是否由兩個乘以大小的print
,而是做主叫方。 將print
函數更改為僅迭代到SIZE_OF_ARRAY
,並將調用它的兩個位置更改為:
print(ptr1, SIZE_OF_ARRAY);
和
print(ptr2, SIZE_OF_ARRAY * 2);
相應地。
現在,我假設您的第二個函數確實為所有 20 個元素分配了值,但如果沒有,則它沒有分配值的那些將繼續包含垃圾。 要繞過它,只需在第二個函數的開頭初始化它們:
int *ptr2 = new int[SIZE_OF_ARRAY * 2];
for (size_t i = 0; i < SIZE_OF_ARRAY * 2; ++ i) ptr2[i] = 0;
通過這兩個更改,您應該獲得所需的行為。
另外,如果你用new[]
分配了一些東西,你需要用delete[]
刪除它,否則你會出現內存泄漏。 在main
的末尾添加這兩行:
delete[] ptr1;
delete[] ptr2;
請注意,在這種情況下使用delete
而不是delete[]
是錯誤的。 如果某物被分配為數組,則必須將其作為數組刪除。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.