Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/forums/c/)
-   -   Returning address in a function (http://www.go4expert.com/forums/returning-address-function-t9118/)

basha_msc 1Mar2008 21:56

Returning address in a function
 
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);

}


technosavvy 5Mar2008 09:49

Re: Returning address in a function
 
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 ..!! :)

aisha.ansari84 5Mar2008 17:21

Re: Returning address in a function
 
ya he is right you should take a pointer to integer instead of reference

asadullah.ansari 12Mar2008 13:32

Re: Returning address in a function
 
Quote:

Originally Posted by basha_msc
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);

}



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.


All times are GMT +5.5. The time now is 17:57.