-5
   int*func();
   int main()
    {
    int i;
    int *ptr;
    ptr=func();
    for(i=0;i<10;i++)
    {
    printf("%d ",*ptr);
    ptr++;
    }
    }

     int* func()
    {
    int arr[10];
    int i;
    for( i=0;i<10;i++)
    arr[i]=i+1;
    return arr;
    }

Why i am not getting my output as 1,2,3,4,5,6,7,8,9,10??

I am returning the address of the array from func() but i am still getting junk values.

Paul R
  • 208,748
  • 37
  • 389
  • 560
CodeHacker
  • 31
  • 6

2 Answers2

1

Wow - aggressive downvoting! Give the new person a chance folks!

The answer is "scope". If you compile with gcc, you get a very obvious warning:

C:\tmp>gcc test.c
test.c: In function `func':
test.c:22: warning: function returns address of local variable

The local variable is lost when the function exits and its memory allocation cleaned up.

If you want to return an array from a function you have to malloc it to create a non-local memory allocation and then return the pointer.

David Ranieri
  • 39,972
  • 7
  • 52
  • 94
Simon G.
  • 6,587
  • 25
  • 30
  • I think the aggressive down-voting is probably due to the fact that there are many duplicate questions on this topic already, so the OP presumably hasn't done any research prior to posting. – Paul R Jan 26 '15 at 09:18
  • apart from malloc cant i use anything else?? – CodeHacker Jan 26 '15 at 09:21
  • Yes, change `int arr[10];` to `static int arr[10];`, [take a look](http://stackoverflow.com/q/572547/1606345) – David Ranieri Jan 26 '15 at 09:23
  • I know the meaning of "SCOPE" but totally lost it in this problem. – CodeHacker Jan 26 '15 at 09:26
  • After changing arr[10] to static if i add a new function func1() in my program which prints all the elements of a array and call it from the func() so whether it will be able to print the elements?? – CodeHacker Jan 26 '15 at 09:33
  • I strongly suggest you **don't** use `static` as a way of working around this problem - it's a bad habit to get into and it results in code that is neither thread-safe nor re-entrant. – Paul R Jan 26 '15 at 09:37
1

You're returning a pointer to a local variable, which results in undefined behaviour.

The most common way to deal with functions that return arrays is to pass in the array from the caller, e.g. fixed version of your code:

void func(int arr[]);

int main()
{
    int arr[10];

    func(arr);

    for (int i = 0; i < 10; i++)
        printf("%d ", arr[i]);

    return 0;
}

void func(int arr[])
{
    for (int i = 0; i < 10; i++)
        arr[i] = i + 1;
}
Paul R
  • 208,748
  • 37
  • 389
  • 560