In C, “strings” are just plain char
arrays. Therefore, you can’t directly concatenate them with other “strings”.
You can use the strcat
function, which appends the string pointed to by src
to the end of the string pointed to by dest
:
char *strcat(char *dest, const char *src);
Here is an example from cplusplus.com:
char str[80]; strcpy(str, "these "); strcat(str, "strings "); strcat(str, "are "); strcat(str, "concatenated.");
For the first parameter, you need to provide the destination buffer itself. The destination buffer must be a char array buffer. E.g.: char buffer[1024];
Make sure that the first parameter has enough space to store what you’re trying to copy into it. If available to you, it is safer to use functions like: strcpy_s
and strcat_s
where you explicitly have to specify the size of the destination buffer.
Note: A string literal cannot be used as a buffer, since it is a constant. Thus, you always have to allocate a char array for the buffer.
The return value of strcat
can simply be ignored, it merely returns the same pointer as was passed in as the first argument. It is there for convenience, and allows you to chain the calls into one line of code:
strcat(strcat(str, foo), bar);
So your problem could be solved as follows:
char *foo = "foo"; char *bar = "bar"; char str[80]; strcpy(str, "TEXT "); strcat(str, foo); strcat(str, bar);