简体   繁体   中英

C++ returning pointer

#include <iostream>
using namespace std;

int* createArray();

int main() {
    int *arr = createArray();
    cout << "Main: " << arr << endl;

    arr[0] = 0;
    arr[1] = 1;

    cout << arr[0] << endl;
    cout << arr[1] << endl;
}

int* createArray() {
    int arr[2];
    cout << "createArray()1: " << arr << endl;
    return arr;
}

I don't understand why if I only call this statement

cout << arr[0] << endl;

or

cout << arr[1] << endl;

can show a correct value. But if I call both statement, it will show

createArray()1: 00AFFAF4
Main: 00AFFAF4
0
11533068  //Don't show 1

The pointer returned by createArray points to a non-existing object. The local array was destroyed when the function returned. When you dereference the dangling pointer in main , the behaviour of your program is undefined.

Solution: Don't ever return pointers or references to local variables. In this case, you could for example return a copy of the array. You cannot return a raw array by value, but you can return a wrapper structure like std::array<int, 2> .

You are returning a pointer to local variable which is destroyed at function block end.

But beware, when you use new operator, you need to use delete somewhere else (atleast without of use of smart pointers).

Solution:

int* createArray() {
    int* arr = new int[2];
    // your code
    return arr;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM