0

Normally a scope of an array in a function ends with it. But if I allocate beforehand then it perfectly returns the array. So what's the difference between allocating array or declaring array? I am writing the code and the place where I am confused. Is it because of dynamic memory allocation of the first declaration or something else. Can someone elaborate please?

#include <bits/stdc++.h>
#define N 10

using namespace std;

int * get_array() {
    int * p = new int[N];
    //|--- by declaring like this, the array was perfectly returned.

    int p[N];
    //|--- but is case of this declaration the array returned showed garbage value in the main function.
    for(int i = 0; i < N; ++i) p[i] = i;
    return p;
}

int main(int argc, char const *argv[])
{
    int * M = get_array();
    for (int i = 0; i < N; ++i) {
        cout << M[i] << endl;
    }
    return 0;
}

1 Answers1

0

In the second case the array is created in the heap of the function, so when you exit the function, that array doesn't exists anymore. In the first case, you're reserving memory space to put your array, so isn't local to the function per se, and you must handle its destruction

alseether
  • 1,889
  • 2
  • 24
  • 39
  • in the first case, is it heap or stack ? – Shaikh Islam Oct 30 '17 at 11:07
  • @ShaikhIslam If i remember correctly, the **pointer** is in the stack, but the real array you've reserved is simply outside, in the *general use* memory, but it belong to the program which has reserved it. – alseether Oct 30 '17 at 11:11