简体   繁体   中英

what's wrong with this string concatenation function

why doesn't this code work properly? this is K&R exercise 5-3

char str[20]= "Hello world";
char str2[5] = "xxx";
int main(void) {
    strcat(str, str2);
    printf("%s", str);
    return 0;
}

void strcat(char *s, char *a) {
    while (*s++);
    while (*s++ = *a++);
}

It's because while(*s++); still increments s even when it hits the NULL string terminator before exiting to the next statement. Try:

while (*s) {
    s++;
}

So that s does not get incremented when s becomes NULL. That way, the first character of a can overwrite the NULL terminator for s .

Postfix increment/decrement have high precedence, but the actual increment or decrement of the operand is delayed (to be accomplished sometime before the statement completes execution). So in the statement y = x * z++; the current value of z is used to evaluate the expression (ie, z++ evaluates to z) and z only incremented after all else is done ( http://www.difranco.net/compsci/C_Operator_Precedence_Table.htm )

Change

while(*s++)

to

while(*s && *(++s));

so that s first increments and then gets checked, in order to have the pointer to the last address.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM