Heap "was not declared in this scope" error

I'm relatively new to C++ and am having a problem with the heap and variable scope. My code looks like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>

using namespace std;

void child();

int main()
{
    int* a = new int;
    *a = 3;
    child();

    return 0;
}

void child()
{
    cout << a << endl;
}


I got the following error when compiling:
In function ‘void child()’:
line 18 error: ‘a’ was not declared in this scope


Could someone please explain to me why this doesn't work, and how to fix it?
Last edited on
because variable 'a' was declared inside 'main', a variable is visible only within the enclosing scope block ( the part of program enclosed by braces )

You can pass 'a' as argument to 'child'

Also notice that cout << a will output an address since 'a' is a pointer and that you have a memory leak because you called 'new' without 'delete'

I suggest you reading the tutorials: http://www.cplusplus.com/doc/tutorial/
So, like this?


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>

using namespace std;

void child(int* b);

int main()
{
    int* a = new int;
    *a = 3;
    child(a);

    return 0;
}

void child(int *b)
{
    cout << *b << endl;
}
I think you have to use

 
delete a;


when you're done with the variable. Maybe in this short program it wouldn't be necessary, as the program would end and the space in memory will be freed, but it's good practice to remember to free any dynamically allocated memory.

(Hope I got that right, I'm new to this as well)
Thanks, Bazzy and Davitosan.
I'm just having a little trouble getting the hang of pointers. The tutorials have helped.
Topic archived. No new replies allowed.