Velocity Reviews > Pointer arithmetic question.

# Pointer arithmetic question.

Ben Bacarisse
Guest
Posts: n/a

 11-02-2012
S R <(E-Mail Removed)> writes:

> On Oct 31, 4:20Â*am, Ben Bacarisse <(E-Mail Removed)> wrote:
>
> [snip]
>
>>
>> Â* Â* Â*char *r = 0;
>> Â* Â* Â*while (*s++ || !r && (r = s - 1) || (*r++ = *t++));

> ^^^^^
> I think there is a problem with the above. Once we reach the end of
> string s, s is not guaranteed to point to a location containing 0 as
> its value, assuming s as being sent in by the caller of the function
> (in your earlier examples you made ",*s =0" which was the correct).
> The concatenation happens through r but the check *s++ is problematic,
> isn't it?

Yes, you're right. I don't know how that got through the test cases
because I had one to cover that situation -- I had the same bug in the
previous version until I added this test case.

There's another bug as well. Because the middle condition is true but
copies no characters, s is incremented once more it needs to be. We have
to assume that s points somewhere big enough for the concatenated string
so incrementing s along with r is safe provided we don't go too far. If
the target is only just big enough, s will be incremented beyond the
specially permitted "one past the end" position.

Oh well... I don't think I'll offer a fix since the "challenge" of
cramming it all in the condition seems a bit old now.

--
Ben.

Prathamesh Kulkarni
Guest
Posts: n/a

 11-02-2012
An attempt for one-line condition for strcat.

char *mystrcat(char *s, char *t)
{
char *r = 0, *temp = s;

while ((*s && s++) || (r == 0 && (r = s) || (*r++ = *t++)))
;
return temp;
}

Prathamesh Kulkarni
Guest
Posts: n/a

 11-02-2012
A one-liner attempt for strcat.
http://pastebin.com/LUYcE46F

Regards,
Prathamesh