A few problems...
1.
foo
is constant here. You cannot modify string literals.
2.
The contract for strcat
is that the first parameter is large enough to fit the concatenated string. So more realistically you'd do something this...
char foo[8] = "foo"; /* Note that buffer size is larger than the string... */
strcat(foo, "bar");
3.
As you might guess, it's not obvious to a newcomer how this is supposed to work. I say there's a reason for this: in general strcat
is considered quite bad. A good C interface for interacting with buffers of potentially arbitrary length will make this a lot more explicit. You might want to look at strncat
or strlcat
which track sizes.
I would say in general though if you're using the strcat
family you're doing something wrong. Each call to strcat
will have to traverse the string to find where the end is. Imagine you are doing a lot of these operations -- it's very easy to imagine something that can easily be done in O(n) steps suddenly turning into O(n2) because of the repeated traversal of the string. If you need to concatenate to a string repeatedly, you should be maintaining a pointer to the current end of the string and doing the copy from there.
Update: Example of how you might do this last suggestion follows...
struct string
{
char *current_end;
size_t bytes_remaining;
};
int
smart_concat(struct string *str, const char *tail)
{
size_t new_length = strlen(tail);
/* Do we have enough space? (include NUL character) */
if (new_length + 1 < str->bytes_remaining)
{
/* Evidently not... */
return -1;
}
/* Copy the string... (including NUL character) */
memcpy(str->current_end, tail, new_length + 1);
/* Update the pointer to the end of our string, and bytes remaining.. */
str->current_end += new_length;
str->bytes_remaining -= new_length;
return 0;
}
Then you might use this as follows:
struct string str;
char buffer[some_size];
/* Initialize the structure to point at our buffer... */
str.current_end = buffer;
str.bytes_remaining = sizeof(buffer);
/* Strictly speaking, you should check the return code for overflow... */
smart_concat(&str, "foo");
smart_concat(&str, "bar");
/* Print out the result: */
puts(buffer);