John Harrison wrote:
>
> "Julie" <> wrote in message
> news:...
> > John Harrison wrote:
> > >
> > > "Mike Mimic" <> wrote in message
> > > news:c87itd$2cp$...
> > > > Hi!
> > > >
> > > > Is it possible to write this (and that it will work):
> > > >
> > > > char *buffer = ... // some array of chars terminated by \0 (allocated
> > > >
> > > > // with new and filled somewhere else)
> > > > int t = ... // some value - how much to delete at the begining
> > > >
> > > > char *rest = new char[strlen(buffer) - t + 1];
> > > > strcpy(rest, buffer + t);
> > > > delete[] buffer;
> > > > buffer = rest;
> > > >
> > > > in this way:
> > > >
> > > > char *buffer = ... // some array of chars terminated by \0 (allocated
> > > >
> > > > // with new and filled somewhere else)
> > > > int t = ... // some value - how much to delete at the begining
> > > >
> > > > strcpy(buffer, buffer + t);
> > > >
> > >
> > > No, the behaviour of strcpy is undefined if the source and destination
> > > strings overlap.
> > >
> > > You can use memmove instead which is guaranteed to work even for
> overlapping
> > > memory blocks
> > >
> > > memmove(buffer, buffer + t, strlen(buffer + t) + 1);
> > >
> > > john
> >
> > Should be:
> >
> > memmove(buffer, buffer + t, (strlen(buffer+t)+1)*sizeof(*buffer));
>
> Why? sizeof(*buffer) is guaranteed to be one. Or are you making a stylistic
> comment?
>
> john
No, stylistic comment, but:
- strlen returns a character count, memmove takes a byte count, multiplying
simply converts from char count to bytes.
- More importantly, if the user changes from ASCII to Unicode (or other mbcs),
then their code is much more portable/convertible.
In this day and age, it is no longer safe to make assumptions that
sizeof('character type') == 1
|