简体   繁体   中英

Why does strcat not work with empty string in C?

Here is my program :-

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(void)
{
    char arrcTest[256] = {0};
    strcat(arrcTest,"Hello");
    sprintf(arrcTest,"%s","World");
    strcat(arrcTest,"!!");
    printf("The String is=> %s\n",arrcTest);
    return 0;
}

I compiled it with gcc version 4.8.3 and got the following output :-

The String is=> World!!

Why is strcat not working first time but it's working properly from second time onwards?

该语句完全覆盖了第一个strcat:

sprintf(arrcTest,"%s","World");

sprintf is not the same as strcat . sprintf formats the string and puts it at the beginning of the buffer. strcat , on the other hand, appends the string to the end of the buffer.

strcat(arrcTest,"Hello");   /* after this statement you have "Hello" in arrcTest */  
sprintf(arrcTest,"%s","World");  /* after this statement you have "World" in arrcTest */
strcat(arrcTest,"!!");    /* after this statement you have "World!!" in arrcTest */

The first strcat is working. Only you overwrote it in the next statement

sprintf(arrcTest,"%s","World");

If you do not want that the first result of strcat would be overwritten then you can write

sprintf( arrcTest + strlen( arrcTest )," %s","World");

The other approaches are

int main(void)
{
    char arrcTest[256] = {0};
    strcat(arrcTest,"Hello");
    strcat(arrcTest, " World");
    strcat(arrcTest,"!!");
    printf("The String is=> %s\n",arrcTest);
    return 0;
}

or

int main(void)
{
    char arrcTest[256] = {0};
    sprintf(arrcTest,"%s %s%s", "Hello", "World", "!!" );
    printf("The String is=> %s\n",arrcTest);
    return 0;
}

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