0

I am trying to return array from a function and want to initialize in new array in main function.

My code isn't showing any error in codeblocks but its also not working.

Here is my code

#include<stdio.h>

int * ReturnArray()
{
    static int *Arr;
    int i;
    for(i=0;i<5;i++)
    {
        Arr[i] = i;
    }

    return Arr;
}

int  main()
{
    int *A,i;
    A = ReturnArray();

    for(i=0;i<5;i++)
    {
        printf("%d",A[i]);
    }

    return 0;
}
Olcay Ertaş
  • 5,987
  • 8
  • 76
  • 112
Vikas Gautam
  • 441
  • 8
  • 22

1 Answers1

1

You have not allocated any memory, so the Arr-Pointer in pointing nowhere.

What you probably want to do is

int * ReturnArray()
{
    int *Arr = malloc(5 * sizeof(int));
    int i;
    for(i=0;i<5;i++)
    {
        Arr[i] = i;
    }

    return Arr;
}

However, you need to free() that memory afterwards.

PhilMasteG
  • 3,095
  • 1
  • 20
  • 27