c++ - 动态分配的数组超出范围错误

标签 c++ arrays

当我尝试将第一个数组的内容复制到 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/

相关文章:

C++ 错误 : expected unqualified-id before '[' token

c++ - 如果被指针引用,非动态变量什么时候会超出范围?

c++ - "Materializing"用于 C++ 类型推断的已知类型的对象

c++ - 如何找到外部变量的链接路径

Javascript按时间倒序对对象数组进行排序

c++ - 恒定时间更改C++中数组的前k个元素?

c++ - 为什么使用 void(unused) (和类似的)而不是无名参数来消除 C++ 函数中的未使用变量警告?

javascript - 使用递归查找数组中的元素 - javascript

php - PHP 错误消息 "Notice: Use of undefined constant"是什么意思?

javascript - 如何使用lodash向数组中的所有对象添加键值对