我想编写一个使用DMA的函数(changeSize),我可以选择将它(数组)的大小更改为我想要的大小,其中oldEls是原始大小,newEls是新大小.如果newEls大于oldEls,我只会在结尾添加零,如果它小于oldEls,我只会截断."ptr"参数需要指向新数组.据我所知,这与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);
}
Run Code Online (Sandbox Code Playgroud)
首先,你newArr在最后调用delete changeSize.你需要删除ptr的旧值(你当前丢弃的).这(可能)是问题所在
虽然我很喜欢,但我想指出你的兴趣std::vector.它基本上是一个可调整大小的数组.
此外,复制原始内存仍然是最好的memcpy,不要浪费你的时间来编写循环只是为了复制ints,只为C++类做到这一点.
编辑:使用std::copy是C++的最佳解决方案,memcpy它可以在可能时使用,否则它与复制对象的for循环相同.
干杯!