I am writing a fake banking program. In the function below I declare a dynamic array.

void trArr(int transactions)
{
    int n;
    string* accUse = new string[transactions];
    return;
}

I try to access the array in a later function but I get the error "not declared at this scope. I thought that the array would be on the heap as opposed to the stack and would still exist after the function returns. Is this wrong?

Recommended Answers

All 3 Replies

The memory is on the heap, but the pointer you use to get to the memory is not. It follows the same rules as any other variable from the same scope. You can save the pointer by returning it from the function:

string* trArr(int transactions)
{
    return new string[transactions];
}

I am writing a fake banking program. In the function below I declare a dynamic array.

void trArr(int transactions)
{
    int n;
    string* accUse = new string[transactions];
    return;
}

I try to access the array in a later function but I get the error "not declared at this scope. I thought that the array would be on the heap as opposed to the stack and would still exist after the function returns. Is this wrong?

here the array is a local variable and it's reference is destroyed as soon as the control leaves the scope though the memory is not deallocated.

so u can't never access the array outside the function.

To access the array, u need to return the reference from the function.

No. The array 'accUse' will only exist within the scope of the function 'trArr'. You should read this.
And why do you need an array of strings? Do you know how to use vectors?

[edit] Too slow... 3 posts in 1 minute ?!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.