我想編寫一個函數(changeSize)使用DMA,在那裏我可以選擇改變它的(的數組的大小),無論我想要什麼,其中oldEls是原始大小,newEls是新的大小。如果newEls比oldEls大,我只想補充零點的到最後,如果它比oldEls小,我只想截斷。 「ptr」參數需要指向新的數組。我的理解是這與C realloc()函數類似。C++:使用動態內存分配寫類似C的realloc()函數的函數(即改變它的大小)
使用下面的代碼,我輸出以下內容:0,0,3,6,0,0,0,0,其中正確的輸出應該是4,2,3,6,0,0, 0,0.我也意識到我的show函數可能不是輸出新數組的最佳函數,因爲我必須顯式聲明數組元素的大小。
在此先感謝。
#include <iostream>
#include <cstdlib>
using namespace std;
void show(const int a[], unsigned elements);
int * copy(const int a[], unsigned els);
void changeSize(int * & ptr, int newEls, int oldEls);
void die(const string & msg);
int main()
{
int arr[4] = {4, 2, 3, 6};
show(arr, 4);
int * newArr = copy(arr, 4);
cout << endl << endl;
changeSize(newArr, 8, 4);
show(newArr, 8);
}
void show(const int a[], unsigned elements)
{
for (int i = 0; i < elements; i++)
cout << a[i] << endl;
}
int * copy(const int a[], unsigned els)
{
int *newArr;
try
{
newArr = new int[els];
}
catch(const bad_alloc &)
{
die("Copy: Alloc Failure");
}
for (int i = 0; i < els; i++)
newArr[i] = a[i];
return newArr;
}
void changeSize(int * & ptr, int newEls, int oldEls)
{
int * newArr;
try
{
newArr = new int[newEls];
for (int i = 0; i < oldEls; i++)
{
newArr[i] = ptr[i];
}
if (newEls > oldEls)
{
for (int k = oldEls; k < newEls; k++)
newArr[k] = 0;
}
}
catch(const bad_alloc &)
{
die("changeSize: Alloc Failure");
}
ptr = newArr;
delete[] newArr;
}
void die(const string & msg)
{
cerr << "Fatal error: " << msg << endl;
exit(EXIT_FAILURE);
}
爲什麼不使用'直接realloc'?或者使用std :: vector? – PaulMcKenzie 2014-11-24 00:31:40
'realloc'不會要求舊的尺寸,也不會將新的空間歸零。 – Deduplicator 2014-11-24 00:38:18
http://ideone.com/wSEv2S可以做這樣的事情..但我不明白你爲什麼要重新發明輪子.. – Brandon 2014-11-24 01:08:21