This is the mail archive of the
gcc-help@gcc.gnu.org
mailing list for the GCC project.
RE: Error with basic string
- From: "Rupert Wood" <me at rupey dot net>
- To: "'Ajay Bansal'" <Ajay_Bansal at infosys dot com>
- Cc: <gcc-help at gcc dot gnu dot org>
- Date: Thu, 23 Jan 2003 18:31:49 -0000
- Subject: RE: Error with basic string
Ajay Bansal wrote:
> char *func(string a, int n)
> {
> a.resize(n);
> return a.begin();
> }
a.begin() is an iterator. You'll have to dereference it to get the
character and then re-reference that for the pointer, i.e. (bracketed
for clarity)
char *func(string a, int n)
{
a.resize(n);
return &(*(a.begin()));
}
*However*
1) you're not passing your string by reference; what you're
telling it to do is to take a copy of string a, resize the
copy to n characters and then return a pointer to the first
character in the copy - i.e. a pointer to memory owned by a
dead object
2) (I'm not an STL guru so take this with a pinch of salt)
I don't think there's a requirement that the string be
stored continuously in memory, except for a read-only copy
between c_str() the next non-const operation. It looks like
you want func to allocate you an n-byte continuous character
buffer in a basic_string and, whilst some implementations will
give you this, I don't think you can assume all will. (But you
probably know this - the comment about changing the return
type?) I can't tell you if G++'s STL plays along.
Rup.