1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Returning address in a function

Discussion in 'C' started by basha_msc, Mar 1, 2008.

  1. basha_msc

    basha_msc New Member

    Joined:
    Nov 12, 2007
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    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 a moderator: Mar 4, 2008
  2. technosavvy

    technosavvy New Member

    Joined:
    Jan 2, 2008
    Messages:
    52
    Likes Received:
    0
    Trophy Points:
    0
    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 ..!! :)
     
  3. aisha.ansari84

    aisha.ansari84 New Member

    Joined:
    Feb 13, 2008
    Messages:
    82
    Likes Received:
    1
    Trophy Points:
    0
    ya he is right you should take a pointer to integer instead of reference
     
  4. asadullah.ansari

    asadullah.ansari TechCake

    Joined:
    Jan 9, 2008
    Messages:
    356
    Likes Received:
    14
    Trophy Points:
    0
    Occupation:
    Developer
    Location:
    NOIDA

    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.
     

Share This Page