473,395 Members | 1,696 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

Problem with C++ vectors

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<intv;

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

Apr 19 '07 #1
5 1666
On 19 Apr, 14:38, vasi...@gmail.com wrote:
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?
It's not at all surprising the vector is in charge of managing the
memory used to store its elements. When you push the second element
onto the vector it will need to resize the memory-area used to store
the elements and will thus reallocate its elements.

There are a number of operations that might cause a vector to
invalidate iterators, and all of them will also invalidate any
pointers to members.

--
Erik Wikström

Apr 19 '07 #2
On Thu, 19 Apr 2007 05:38:24 -0700, vasim98 wrote:
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.
Why should this behaviour surprise you? A vector is not an array and
nothing in the standard says that elements of a vector may not be moved
about in memory.
The "ptr_v" addressing the 1st element of vector loses it's value when
an other element is inserted in the vector!
With standard containers it is generally disastrous to access elements
via raw pointers; rather, iterators should be used - and there are clear
rules as to when an iterator is "invalidated" (in the sense that the
pointer in your example apparently is) by some operation.

Any good book on the Standard Library ought to clarify this further.

[...]

Cheers,

--
Lionel B
Apr 19 '07 #3
va*****@gmail.com wrote:
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!!!
Invalidated. Any use of the pointer is undefined behavior. If
you need to maintain pointers in such cases, you'll either need
a different type of container, or to avoid increasing the size
of the vector.
Whereas in case of array, the pointer to already stored element is
preserved even if you insert elements to that array.
Whereas in the case of a C-style array, you cannot insert
elements, so the question doesn't come up. If you use a vector
like you would a C-style array, declaring its size up front, you
won't have any problems either.
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?
Try implementing a simple vector class yourself. Or try doing
the equivalent using new int[], and you'll probably get the same
effect. The standard says that iterators, pointers and
references to elements in the vector may be invalidated anytime
the capacity of the vector is increased for the simple reason
that you can't implement anything reasonable otherwise.

--
James Kanze (GABI Software) email:ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

Apr 19 '07 #4
va*****@gmail.com wrote:
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!!!
Invalidated. Any use of the pointer is undefined behavior. If
you need to maintain pointers in such cases, you'll either need
a different type of container, or to avoid increasing the size
of the vector.
Whereas in case of array, the pointer to already stored element is
preserved even if you insert elements to that array.
Whereas in the case of a C-style array, you cannot insert
elements, so the question doesn't come up. If you use a vector
like you would a C-style array, declaring its size up front, you
won't have any problems either.
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?
Try implementing a simple vector class yourself. Or try doing
the equivalent using new int[], and you'll probably get the same
effect. The standard says that iterators, pointers and
references to elements in the vector may be invalidated anytime
the capacity of the vector is increased for the simple reason
that you can't implement anything reasonable otherwise.

--
James Kanze (GABI Software) email:ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

Apr 19 '07 #5
On Apr 19, 8:38 am, vasi...@gmail.com wrote:
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!!!
As expected. Although its not lost. Your code lost it - yes.
The vector has member functions begin(), front(), back() and end()
that will return corresponding iterators.
>
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 that surprise you? Is std::vector not dynamic?

Did you not know that:
std::vector< int v(40);
generates a container of 40 default initialized elements?
yet its still a dynamic container?
std::vector< int v(40, 99);
generates the same with whatever initialized integer value you choose
(other than 99)?
std::vector< std::string vs(1000, "default string"); // what the
hell?
>
Why does this happen??? Any expert of C++ data structures can explain?

//
************************************************** ***************************************
#include <iostream>
#include <vector>
using namespace std;

int main(int)
{

vector<intv;

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

Apr 19 '07 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

10
by: Michael Aramini | last post by:
I need to represent 1D and 2D arrays of numeric or bool types in a C++ program. The sizes of the arrays in my intended application are dynamic in the sense that they are not known at compile time,...
5
by: Pratyush | last post by:
Hi, Suppose there is a vector of objects of class A, i.e., std::vector<A> vec_A(N); The class A satisifies all the STL vector requirements. Now I wish to add some attributes for each of the...
1
by: Dennis | last post by:
Hi I'm trying to implement a vector of vectors where find can be used to find a vector<double> in the vectors of vectors, that is hard to understand i guess. What I mean is that I got a vector...
5
by: Computer Whizz | last post by:
I was reading through Accelerated C++ at work when I read through the first mention of Vectors, giving us certain functions etc. Is there any benefit of Arrays over Vectors? Since all Vectors...
0
by: rokuingh | last post by:
ok, so i've been working on this one for quite a while, and the code is very big so i'm just going to give the relevant parts. this is a program that builds polymers (chemical structures of repeated...
5
by: madhu | last post by:
http://msdn2.microsoft.com/en-us/library/fs5a18ce(VS.80).aspx vector <intv1; v1.push_back( 10 ); //adds 10 to the tail v1.push_back( 20 ); //adds 20 to the tail cout << "The size of v1 is " <<...
3
Digital Don
by: Digital Don | last post by:
I have a problem sending the Vectors as Referencial parameters..i.e. I am having a struct vector struct board { int r; int c; };
4
by: 9966 | last post by:
Greetings, I'm currently facing a problem on how to compare 2 vector's elements. For example, assuming we have declared 2 integer type vectors: vector <int> v1; vector <int> v2; and both...
4
by: demonbunny666 | last post by:
I'm trying to get this program to work, but I am running into a problem and as hard as I try I can't figure it out. It compiles fine( VS Studio 6.0) but when it executes a problem occurs, something...
2
by: joeme | last post by:
How would one using STL do the following tasks: 1) merge 2 sorted vectors with dupes, result shall be sorted 2) merge 2 sorted vectors without dupes, result shall be sorted 3) merge 2...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.