Search code examples
cpointerspostfix-operator

Finding end of string: *s++ VS *s then s++


I'm writing a simple string concatenation program.

The program works the way I have posted it. However, I first wrote it using the following code to find the end of the string:

while (*s++)
    ;

However, that method didn't work. The strings I passed to it weren't copied correctly. Specifically, I tried to copy "abc" to a char[] variable that held "\0".

From reading the C K&R book, it looks like it should work. That compact form should take the following steps.

  1. *s is compared with '\0'
  2. s points to the next address

So why doesn't it work? I am compiling with gcc on Debian.

I found that this version does work:

strncat(char *s, const char *t, int n)
{
    char *s_start = s;

    while (*s)
        s++;

    for ( ; n > 0 && *t; n--, s++, t++)
        *s = *t;

    *(s++) = '\0';

    return s_start;
}

Thanks in advance.


Solution

  • After the end of while (*s++);, s points to the character after the null terminator. Take that into account in the code that follows.