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?
#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|
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).
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.