Returning address in a function

Newbie Member
1Mar2008,21:56   #1
basha_msc's Avatar
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
Contributor
5Mar2008,09:49   #2
technosavvy's Avatar
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 ..!!
Contributor
5Mar2008,17:21   #3
aisha.ansari84's Avatar
ya he is right you should take a pointer to integer instead of reference
TechCake
12Mar2008,13:32   #4
asadullah.ansari's Avatar
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.