0

I was trying to pass the array address from the function to the main function that's happening perfectly. But when I dereference the address in main(), I am getting junk values. I am guessing that the variables in the array_address memory lives only within the scope of the function. If this is the case, how do you return an array generated within a function to another function?

Here's my code:

int* letssee(int something)
{
    int* array_address;
    int a[10], i=0;
    array_address = &a[0];

    for (i; i<something;i++)
    {
            *(array_address+i) = i;
            printf("\n%p, %d",(array_address+i), *(array_address+i));   

    }

    return array_address;

     }

int main()

{
    int i= 5,j;
    int* catch_address;
    catch_address = letssee(i);

    printf("\n");
    for (j= 0; j<i; j++)
    {
    printf("%p, %d\n", (catch_address+j),*(catch_address+j));  
    } 

    return 0;
}
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Mathews_M_J
  • 457
  • 4
  • 15
  • 4
    Returning a pointer or reference to a non-static local variable results in undefined behavior because the variable is no longer valid after the function returns. – Captain Obvlious Sep 22 '14 at 01:47
  • Oh.. so all I have to do is make a static array? And then pass that? – Mathews_M_J Sep 22 '14 at 01:50
  • 1
    no, don't do that... that's recipe for disaster later on. why don't you allocate a buffer via new (or pass the buffer in from the caller) – thang Sep 22 '14 at 01:52

1 Answers1

0

you can't return an array defined in a function as it is allocated on the stack and will disappear after the function has finished. Instead you allocate memory

int *array_address = malloc(sizeof(int) * 10);

however, you have to manage the memory, meaning you have to "free" it when you are finished with it, otherwise you will leak memory

The other approach is to pass the memory preallocated into a function (whether it be via malloc or the stack or global)

int* letsee(int something, int* array_address, int count);

if you simply make the array static, you are effectively making a global variable, multiple calls to the function will return the SAME address and may cause strange behaviour if you are expecting new arrays for each call.

Keith Nicholas
  • 43,549
  • 15
  • 93
  • 156