I am trying to return the address of a local variable but i can't. my code : Code: #include<iostream> using namespace std; int &fun(int , int , int); main() { int &p; int a,b,c; p = &fun(a,b,c); a = *p; b = *(p+1); c = *(p+2); } int &fun(int a , int b , int c) { int A[3]; A[0] = a+1; A[1] = b+1; A[2] = c+1; return(A); }
don't u think ur code is broken... Code: int A[3]; this variable is local to the function and u r trying to return its base address... and that too using Code: int & ...this shud be replaced by int *... Code: int & means reference and u are passing an addresss..just analyse ur code and u will understand the rest ..!!
First your code will not work at all except returning local address as per told by technosavvy. Just correct it. Now you should never return address of local variable. When you are calling function stack frame will create. when it's runninf the line 'return' then all local variables will be deleted. Just think if you are returning the address of local variables which is already deleted.