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?
initArrayis returning the address of local array which ceases to exist after the function returns. This is an undefined behaviour.To make the variable
apersistent even when the function returns you can either:static