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?

2

4 Answers 4

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
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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;
}

1 Comment

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.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.