David
David

Reputation: 21

Why all pointers in my vector are pointing on the same element?

it seems like I have a fundamental problem in understanding pointers in C++. In my understanding, the following code example should print "53" in the console, but instead it prints "33".

// Example program
#include <iostream>
#include <vector>

int main()
{
  std::vector<int*> v;
  {
    int z = 5;
    v.push_back(&z);
  }
  
  {
    int a = 3;
    v.push_back(&a);
  }
  std::cout << *v[0] << *v[1] << std::endl;
}

I originally had this problem in a bigger project I'm currently working on and I recognized that if I'm doing it this way, all pointers I added previously point to the same element as the last one. But why? I thought that if i add two pointers which point to different integers, they will stay different after adding them to a vector.

Upvotes: 1

Views: 66

Answers (2)

tdao
tdao

Reputation: 17668

The problem was with your scoping. Remove the scopes and you get the expected behaviour:

std::vector<int *> v;
int z = 5;
v.push_back(&z);

int a = 3;
v.push_back(&a);
std::cout << *v[0] << *v[1] << std::endl;

Original code has undefined behaviour:

  std::vector<int*> v;
  {
    int z = 5;
    v.push_back(&z);
  } // here z no longer exists, so you can't dereference it later via *v[0]

Upvotes: 2

John Zwinck
John Zwinck

Reputation: 249133

This:

{
  int a = 3;
  v.push_back(&a);
}

Results in undefined behavior: you are storing the address of a temporary and using it later. This means anything could happen: the program could print "I'm sorry David, I can't do that."

As soon as the scope ends (with }), the lifetime of a ends, and the address it used to occupy is available to be reused. And that is what happens in your code, the same address gets reused so you end up storing the same address twice. But again, undefined behavior means anything could happen. For example, if I compile with optimization enabled on my computer it prints "33" but if I disable optimization it prints "53".

Upvotes: 4

Related Questions