Need some help with basic dynamic mem. allocation

Hi all,

Can't get more basic than this. I'm getting an out of scope error in my copy function, when I try to copy the contents of the first array into the DMA one. The try-catch block is required.

Thanks.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#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);

}
Edit: found the answer. Shouldn't have declared int * newArr inside of my try block.
Topic archived. No new replies allowed.