0

I get a problem about pointer in C++. The code is:

int * initArray() {
    int a [2];

    a[0] = 1;
    a[1] = 2;
    return a;
}


int main () {
    int * b = initArray();

    cout << b << "---" << *(b) << endl;
    cout << b + 1<< "---" << *(b + 1) << endl;
}

The output is

0021FC20---1
0021FC24---1431629120

You can see that the value is wrong.

When I try to put the init array code into main function, it runs correctly.

Could you tell what wrong in my code?

codaddict
  • 445,704
  • 82
  • 492
  • 529
kaka
  • 13
  • 1
  • possible duplicate of [return pointer to data declared in function](http://stackoverflow.com/questions/2320551/return-pointer-to-data-declared-in-function) – Paul R Apr 30 '12 at 10:35
  • Since you're using C++, just use a `std::vector`. – jamesdlin Apr 30 '12 at 11:20

4 Answers4

8

initArray is returning the address of local array which ceases to exist after the function returns. This is an undefined behaviour.

To make the variable a persistent even when the function returns you can either:

  • declare it as static
  • make it global
  • dynamically allocate it
codaddict
  • 445,704
  • 82
  • 492
  • 529
3

A solution to achieve what you are trying to do is:

int * initArray() {
    int* a = new int[2];

    a[0] = 1;
    a[1] = 2;
    return a;
}

Since the memory is manually allocated, it will persist and the construction should be valid. Yeah, in your case, the memory was allocated automatically and deleted at the end of the function resulting in an undefined behaviour.

Morwenn
  • 21,684
  • 12
  • 93
  • 152
1

a is local to the initArray method. Once the method returns, a is no longer valid, so the pointer returned by initArray is no longer valid.

You need to allocate the array in your main method instead, then pass a pointer into the initArray method:

void initArray(int *a) {
    a[0] = 1;
    a[1] = 2;
}

int main () {
    int b[2];
    initArray(b);

    cout << b << "---" << *(b) << endl;
    cout << b + 1<< "---" << *(b + 1) << endl;
}
qbert220
  • 11,220
  • 4
  • 31
  • 31
  • I'd feel more comfortable with this answer if you passed the size of the array to `initArray`. Maybe the size is always going to be fixed in this case, but it's still better to encourage good habits earlier. – jamesdlin Apr 30 '12 at 11:23
0

your array int a[2] is a local array which is deallocated as the function exists.

giorashc
  • 13,691
  • 3
  • 35
  • 71