Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I concatenate const/literal strings in C?

I'm working in C, and I have to concatenate a few things.

Right now I have this:

message = strcat("TEXT ", var);  message2 = strcat(strcat("TEXT ", foo), strcat(" TEXT ", bar)); 

Now if you have experience in C I'm sure you realize that this gives you a segmentation fault when you try to run it. So how do I work around that?

like image 725
The.Anti.9 Avatar asked Nov 21 '08 13:11

The.Anti.9


People also ask

How do I concatenate strings in C?

In C, the strcat() function is used to concatenate two strings. It concatenates one string (the source) to the end of another string (the destination). The pointer of the source string is appended to the end of the destination string, thus concatenating both strings.

Can we add two strings in C?

As you know, the best way to concatenate two strings in C programming is by using the strcat() function.

How do you concatenate strings?

Concatenation is the process of appending one string to the end of another string. You concatenate strings by using the + operator. For string literals and string constants, concatenation occurs at compile time; no run-time concatenation occurs.

Is concatenating two strings a constant time operation?

Yes, in your case*1 string concatenation requires all characters to be copied, this is a O(N+M) operation (where N and M are the sizes of the input strings). M appends of the same word will trend to O(M^2) time therefor.


1 Answers

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); 
like image 173
Brian R. Bondy Avatar answered Nov 28 '22 18:11

Brian R. Bondy