gpt4 book ai didi

C++:使用动态内存分配编写类似于 C realloc() 函数的函数(即更改其大小)

转载 作者:行者123 更新时间:2023-11-30 01:16:13 26 4
gpt4 key购买 nike

我想编写一个使用 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);

}

最佳答案

首先,您在 changeSize 末尾对 newArr 调用 delete。您需要删除 ptr 的旧值(您当前丢弃的)。这就是(可能)问题

虽然我在这里,但我想指出您对 std::vector 的兴趣。它基本上是一个可调整大小的数组。

此外,复制原始内存块仍然最好使用 memcpy 完成,不要浪费时间编写 for 循环来复制 ints,只对 C++ 类执行此操作。

编辑:使用std::copy 是C++ 的最佳解决方案,它尽可能使用memcpy,否则与复制对象的 for 循环。

干杯!

关于C++:使用动态内存分配编写类似于 C realloc() 函数的函数(即更改其大小),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27096154/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com