V
vasim98
I am surprised to see the output of the following C++ program using
vectors. The program is so simple. An element is pushed in a vector
"v" and the pointer to this element is obtained as "ptr_v". Then an
other element is pushed in the vector and after that the pointer
"ptr_v" to the earlier element is lost!!!
Whereas in case of array, the pointer to already stored element is
preserved even if you insert elements to that array. You can try
running this simple program and see the output.
The "ptr_v" addressing the 1st element of vector loses it's value when
an other element is inserted in the vector!
Why does this happen??? Any expert of C++ data structures can explain?
//
*****************************************************************************************
#include <iostream>
#include <vector>
using namespace std;
int main(int)
{
vector<int> v;
v.push_back(40);
int *ptr_v;
ptr_v = &v.at(0);
cout<<"Value = "<<*ptr_v<<endl;
cout<<"Adress of ptr is "<<ptr_v<<endl;
v.push_back(98);
cout<<"Adress of ptr is still "<<ptr_v<<endl;
cout<<"Value = "<<*ptr_v<<endl;
//*************************************
cout<<"......Now for array......"<<endl;
int array[10];
array[0] = 40;
int *ptr_array;
ptr_array = &array[0];
cout<<"Value = "<<*ptr_array<<endl;
cout<<"Adress of ptr is "<<ptr_array<<endl;
array[1] = 98;
cout<<"Adress of ptr is still "<<ptr_array<<endl;
cout<<"Value = "<<*ptr_array<<endl;
return 0;
}
//
********************************************************************************************
Thanks
Waseem
vectors. The program is so simple. An element is pushed in a vector
"v" and the pointer to this element is obtained as "ptr_v". Then an
other element is pushed in the vector and after that the pointer
"ptr_v" to the earlier element is lost!!!
Whereas in case of array, the pointer to already stored element is
preserved even if you insert elements to that array. You can try
running this simple program and see the output.
The "ptr_v" addressing the 1st element of vector loses it's value when
an other element is inserted in the vector!
Why does this happen??? Any expert of C++ data structures can explain?
//
*****************************************************************************************
#include <iostream>
#include <vector>
using namespace std;
int main(int)
{
vector<int> v;
v.push_back(40);
int *ptr_v;
ptr_v = &v.at(0);
cout<<"Value = "<<*ptr_v<<endl;
cout<<"Adress of ptr is "<<ptr_v<<endl;
v.push_back(98);
cout<<"Adress of ptr is still "<<ptr_v<<endl;
cout<<"Value = "<<*ptr_v<<endl;
//*************************************
cout<<"......Now for array......"<<endl;
int array[10];
array[0] = 40;
int *ptr_array;
ptr_array = &array[0];
cout<<"Value = "<<*ptr_array<<endl;
cout<<"Adress of ptr is "<<ptr_array<<endl;
array[1] = 98;
cout<<"Adress of ptr is still "<<ptr_array<<endl;
cout<<"Value = "<<*ptr_array<<endl;
return 0;
}
//
********************************************************************************************
Thanks
Waseem