This is the mail archive of the gcc-help@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

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.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]