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
  • 330,190
  • 66
  • 504
  • 555
Mathews_M_J
  • 429
  • 4
  • 14

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
  • 42,517
  • 15
  • 87
  • 149