-3

I have tried to implement a simple function which returns the pointer to first element in array.

#include<iostream>
using namespace std;
int * func(int n)
{
    int arr[n];
    for (int a = 0; a <n; a++)
    {
        arr[a]=a;
    }
    return arr;
}
int main()
{
    int n;
    cin>>n;
    int * arr=func(n);
    for (int i = 0; i <n; i++)
    {
        cout<<*(arr+i)<<endl;
    }

 }

I have assumed that array occupies contiguous block of memory,then why the output of this program isn't what expected.

if n=10 then output is

0
-1216233191
-1215824576
-1215824576
-1215855028
-1215820256
-1074779464
-1215820256
-1074779464
134514382

1 Answers1

2
int * func(int n)
{
    int arr[n];       <<<<<<<<<<<<<<<local variable to this function.
    for (int a = 0; a <n; a++)
    {
        arr[a]=a;
    }
    return arr;
}

You should not return address of local variables...

ravi
  • 10,994
  • 1
  • 18
  • 36