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?
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.
If you don't have initialize c[0] = '\0';, strcat will seek until the first '\0' before inserting into c.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With