vector<int> vi(3);
    for (int i=0; i<vi.size(); i++)
    {
        cout << vi[i] << endl;
    }

output1:
0
0
0

vector<int *> vi(3);
    for (int i=0; i<vi.size(); i++)
    {
        cout << vi[i] << endl;
    }

output2:
0
0
0

vector<int *> vi(3);
    for (int i=0; i<vi.size(); i++)
    {
        cout << &vi[i] << endl;
    }

output3:
0x2b10b0
0x2b10b4
0x2b10b8

I don't understand why don't i see a difference in the outputs for parts 1 and 2. My expectation was that for part 2, since I have declared a vector of pointers to int, I should see something like output 3 but I don't. Could someone explain me why is it so.

The reason why I did this experiment was since I wanted to initialize a vector of pointers to float. I then want to pass these pointers to some functions that can modify values pointed to by these pointers. I shall then be using these values later in my program.

Edited 7 Years Ago by axed: n/a

vector<int> vi(3);
    for (int i=0; i<vi.size(); i++)
    {
        cout << vi[i] << endl;
    }

output1:
0
0
0

vector<int *> vi(3);
    for (int i=0; i<vi.size(); i++)
    {
        cout << vi[i] << endl;
    }

output2:
0
0
0

vector<int *> vi(3);
    for (int i=0; i<vi.size(); i++)
    {
        cout << &vi[i] << endl;
    }

output3:
0x2b10b0
0x2b10b4
0x2b10b8

I don't understand why don't i see a difference in the outputs for parts 1 and 2. My expectation was that for part 2, since I have declared a vector of pointers to int, I should see something like output 3 but I don't. Could someone explain me why is it so.

The reason why I did this experiment was since I wanted to initialize a vector of pointers to float. I then want to pass these pointers to some functions that can modify values pointed to by these pointers. I shall then be using these values later in my program.

It seems like you are not populating the vector in output one and two, and in output 3 you are just printing out the allocated memory location for the vector

Ok, so I tried to populate, but this gives a seg fault on the marked line,

vector<int *> vi(3);
    for (int i=0; i<(int)vi.size(); i++)
    {   
        *vi[i] = 0;
        cout << &vi[i] << endl;
    }

Edited 7 Years Ago by axed: n/a

Just a segmentation fault. When I debug I find that it is on the line marked in red.

This article has been dead for over six months. Start a new discussion instead.