In article <pan.2007.07.25.08.34.02.890128@gmail.com>,
geek.arnuld@gmail.com says...
[ ... ]
Quote:
#include <iostream>
#include <vector>
#include <string>
>
int main()
{
std::vector<std::string*psvec;
std::string input_string;
std::string* ps;
As has already been pointed out, this has type 'std::string *', but it's
not really a pointer to a string -- it's just an unitialized pointer.
Quote:
while(std::cin >input_string)
{
*ps = input_string;
This really needs to allocate a new string and copy the input_string
into the new string, something like:
ps = new string(input_string);
As it stands right now, it's _trying_ to take wherever the uninitialized
pointer happens to point at, and treat it as if there was a string
there. If you're lucky, it'll point to somewhere that's not readable or
writable, so your program will die immediately when you try to do that
-- but chances of being that lucky aren't very high. The alternative is
that it sort of seems to work for a while, overwriting memory that
doesn't belong to it. That inevitably leads to eventual problems, but
it's hard to predict when they'll become visible -- Murphy's law being
what it is, you'll usually find out about it by the program dying a
horrible death just as you're showing it to the person who's in the best
position to fire you...
Quote:
/* printing the strings pointed by the pointers in the vector*/
for(std::vector<std::string*>::const_iterator iter = psvec.begin();
iter != psvec.end(); ++iter)
{
std::cout << "string: " << **iter
<< " size: " << (*iter).size() /* error is here */
<< std::endl;
/* double-defrenced operator because it points to a pointer
rather than a value */
}
>
/* i was thinking of using "std::copy" from <algorithmand
"ostream_iterator" from <sstreamfrom but was not able to
understand the peculiar mechanism of both of them */
They're going to be pretty tough to apply in a case like this -- for the
most part, the standard containers and algorithms expect to work with
value-like objects, not with pointers. By value-like objects, I mean
things that it's free to copy, assign, etc. There's an implicit
assumption that such operations are also relatively cheap.
--
Later,
Jerry.
The universe is a figment of its own imagination.