pointer and scope question

Apr 8, 2016 at 3:10pm
Hi,
Below I create an array in create_array() and pass the ptr back to main. The pointer addresses have remained the same, in main, create_array(), and back to main again. The pointer returned to main now points to garbage values even though its address has been unchanged. Is this because the function create_array has gone out of scope?

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
#include<iostream>
#include<array>

int * create_array()
{

int my_array[30];
int * n_ptr = my_array;
std::cout<<"n_ptr:"<<n_ptr<<std::endl;
for (int i = 0;i<30;++i)
{
	*n_ptr = i *3;
	++n_ptr;
}
n_ptr = my_array;
for(int i=0;i<30;++i)
{
std::cout<<*n_ptr<<"|";
++n_ptr;
}
n_ptr = my_array;
std::cout<<"n_ptr:"<<n_ptr;
std::cout<<std::endl<<"---"<<std::endl;

return n_ptr;
}


int main()
{
	int * n_ptr;
	n_ptr = create_array();
	std::cout<<"n_ptr returned to main fx"<<n_ptr<<std::endl;
	for(int i=0;i<30;++i)
	{
	std::cout<<*n_ptr<<"|";
	++n_ptr;
	}
	return 0;
}




n_ptr:0x23fd50
0|3|6|9|12|15|18|21|24|27|30|33|36|39|42|45|48|51|54|57|60|63|66|69|72|75|78|81|84|87|n_ptr:0x23fd50
---
n_ptr returned to main fx0x23fd50
-45056|32757|4738944|0|1509702912|32766|4743176|0|4738944|0|-45056|32757|2358816|0|0|0|0|0|0|0|0|0|4639175|0|-45056|32757|4198747|0|-45056|32757|
Apr 8, 2016 at 3:27pm
It's because the array my_array has gone out of scope (and thus been destroyed and the memory made available for something else to write over the top of).
Apr 8, 2016 at 3:33pm
(Intuitive code indentation, please.)

Local variables are in stack memory and cease to exist when execution leaves the scope. Your 'my_array' is a function local.

When a function is called, memory is allocated from stack for its arguments, return value and local variables. When the function returns, the memory is deallocated.
Apr 8, 2016 at 4:18pm
Thanks I thought as much.
Please explain this to me:
(Intuitive code indentation, please.)

If it helps me make better questions --

Apr 8, 2016 at 4:52pm
Please explain this to me:
(Intuitive code indentation, please.)

That simply means please use a consistent indentation style.

Some of your code within functions is left justified (ugly). Some is not.
One of your for loops is indented (good), most are not (bad).

Inconsistent indentation makes your code hard to read.



Apr 8, 2016 at 7:03pm
Thx
Topic archived. No new replies allowed.