Pankaj Goyal
Pankaj Goyal

Reputation: 1548

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?

Upvotes: 2

Views: 1666

Answers (3)

Vlad from Moscow
Vlad from Moscow

Reputation: 311088

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;
}

Upvotes: 1

edtheprogrammerguy
edtheprogrammerguy

Reputation: 6049

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 */

Upvotes: 1

A B
A B

Reputation: 4158

This statement is completely overwriting the first strcat:

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

Upvotes: 3

Related Questions