Returning address in a function

basha_msc's Avatar
Newbie Member
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);

}

Last edited by shabbir; 4Mar2008 at 11:21.. Reason: Code block - http://www.go4expert.com/forums/misc.php?do=bbcode#code
0
technosavvy's Avatar
Contributor
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 ..!!
0
aisha.ansari84's Avatar, Join Date: Feb 2008
Contributor
ya he is right you should take a pointer to integer instead of reference
0
asadullah.ansari's Avatar, Join Date: Jan 2008
TechCake
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.