I'm having trouble understanding the scope/"life-expectancy" of local data pointed to by a pointer that is then returned.
1 2 3 4 5 6 7 8 9 10 11 12 13
|
int** GetTable(){
int table1[]={1,2,3};
int table2[]={4,5,6};
int table3[]={7,8,9};
int* table[]={table1,table2,table3};
return table;
}
int main(){
int** table=GetTable();
cout << *table[2] << endl;
cout << *table[1] << endl;
return 0;
}
|
When I compile this code, the compiler warns me that I am returning the address of a local/temporary variable, and that makes sense to me. However, if this is true (which it is), why is it that the first cout statement prints 7 to the console. As far as I can tell, it shouldn't know that the address held by table[2] contains the integer 7. Or at least, it shouldn't contain the integer 7, rather it should contain some junk value, since, at "return table;", the data should be destroyed.
My next question is, if the first cout statement executes properly, why is it that the second cout statement does not? The first cout statement prints 7, while the second cout statement prints a junk value; something I expected to happen for both, not just the one, cout statement.
Thanks guys, have a good one.