Error with basic string

Rupert Wood
Thu Jan 23 18:32:00 GMT 2003

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)
        return &(*(a.begin()));


    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.


More information about the Gcc-help mailing list