Reputation: 121
I have the following code to demonstrate my question:
#include <iostream>
#include <queue>
using namespace std;
int main(int argc, char* argv[]){
queue<int> numbers;
for (int i = 0; i < 10; i++) {
numbers.push(i);
}
int temp = 10;
int *last = &temp;
for(int j = 0; j < 10; j++) {
cout << *last << endl;
int i = numbers.front();
cout << *last << endl << endl;
numbers.pop();
last = &i;
}
return 0;
}
Which will print out:
10
10
0
1
1
2
2
3
3
4
4
5
5
6
6
7
7
8
8
9
I have some confusion on why the pointer last
is being reassigned whenever int i
changes. What I want is for for last
to hold a reference to the last element - but am having trouble. I would guess that the pointer is pointing to the value of i
- and changes when i
changes. But i
is inside the scope of the for loop, so I'm not exactly sure whats going on here.
Upvotes: 0
Views: 74
Reputation: 311048
Though the program works because the address of local variable i is not being changed nevertheless the program has undefined behaviour becuase in each iteration of the loop except the first iteration pointer last refers to non alive object in statement
cout << *last << endl;
due to the assignment
last = &i;
A correct loop could look the following way
for(int j = 0; j < 10; j++) {
cout << *last << endl;
int i = numbers.front();
cout << *last << endl << endl;
numbers.pop();
*last = i;
^^^^^^^^^^^
}
Upvotes: 2