Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why am I getting junk characters when I concat a string?

Tags:

c

This is my code

    char *c[strlen(a) + strlen(b) + 2];
    strcat(c, a);
    strcat(c, "+");
    strcat(c, b);

The resulting string c has some junk characters in the beginning, followed by the concatenated string. What did I do wrong?

like image 366
mrburns Avatar asked Nov 18 '25 14:11

mrburns


2 Answers

It should be:

char *c = malloc (sizeof (char) * (strlen (a) + strlen (b) + 2));
c[0] = '\0';
strcat(c, a);
strcat(c, "+");
strcat(c, b);

The cause of the failure of your routine is because you have done :

char *c[strlen(a) + strlen (b) + 2];

which declare c as an array of pointers, and also not initialized the array with a '\0'. It should be like

char c[strlen(a) + strlen (b) + 2];

You also have to initialize the array with a null string, as strcat would find the '\0' at the time of concatenation.

Note that there is no problem in execution in error in char *c[strlen(a) + strlen (b) + 2]; as each location would have 4 bytes in length, so the array can accommodate the characters in it. But this is not correct.

like image 200
phoxis Avatar answered Nov 20 '25 05:11

phoxis


If you don't have initialize c[0] = '\0';, strcat will seek until the first '\0' before inserting into c.

like image 29
John Percival Hackworth Avatar answered Nov 20 '25 03:11

John Percival Hackworth