当我尝试将第一个数组的内容复制到 DMA 数组时,我的复制函数出现了超出范围的错误。 try-catch block 是必需的。
#include <iostream>
#include <cstdlib>
using namespace std;
void show( const int a[], unsigned elements );
int * copy( const int a[], unsigned els );
void die(const string & msg);
int main()
{
int arr[4] = {4, 2, 3, 6};
show(arr, 4);
int * newArr = copy(arr, 4);
}
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 )
{
try
{
int * newArr = new int[els];
}
catch(const bad_alloc &)
{
die("Alloc Failure");
}
for (int i = 0; i < els; i++)
newArr[i] = a[i];
return newArr;
}
void die(const string & msg)
{
cerr << "Fatal error: " << msg << endl;
exit(EXIT_FAILURE);
}
最佳答案
如果您在 try
block 中声明变量,那么它只能在那里访问。您可以通过将声明移到 block 外来解决这个问题。
int *newArr;
try
{
newArr = new int[els];
}
catch(const bad_alloc &)
{
die("Alloc Failure");
}
for (int i = 0; i < els; i++)
newArr[i] = a[i];
或者将剩余的代码移到 try
中。
try
{
int *newArr = new int[els];
for (int i = 0; i < els; i++)
newArr[i] = a[i];
return newArr;
}
catch(const bad_alloc &)
{
die("Alloc Failure");
}
关于c++ - 动态分配的数组超出范围错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27093992/