Your approach cannot be used to return the concatenated string: you would return a pointer to a local array that is no longer valid once the function returns, furthermore, you do not check for buffer overflow.

Here is a quick and dirty version that allocates memory:

#include <stdlib.h>  
#include <string.h>

char *concatenate(const char *a, const char *b, const char *c) {
    return strcat(strcat(strcpy(malloc(strlen(a) + strlen(b) + strlen(c) +  1,
                                a), b), c);
}

Here is a more elaborate version using memcpy and testing for malloc failure:

#include <stdlib.h>  
#include <string.h>

char *concatenate(const char *a, const char *b, const char *c) {
    size_t alen = strlen(a);
    size_t blen = strlen(b);
    size_t clen = strlen(c);
    char *res = malloc(alen + blen + clen + 1);
    if (res) {
        memcpy(res, a, alen);
        memcpy(res + alen, b, blen);
        memcpy(res + alen + blen, c, clen + 1);
    }
    return res;
}

It should be more efficient since it does not perform the extra scans strcpy and strcat do, but only careful benchmarking can prove if it is a real improvement over the simple version above.

If you need to concatenate 3 strings into an existing buffer, a very simple solution is:

char dest[DEST_SIZE];

snprintf(dest, sizeof dest, "%s%s%s", a, b, c);

Many systems (linux, GNU, BSD) have an asprintf() function defined that allocates memory for the resulting string:

int asprintf(char **strp, const char *fmt, ...);

Using this function, you can concatenate the three strings quite simply:

#define _GNU_SOURCE
#include <stdio.h>  

char *concatenate(const char *a, const char *b, const char *c) {
    char *p;
    return (asprintf(&p, "%s%s%s", a, b, c) >= 0) ? p : NULL;
}
Answer from chqrlie on Stack Overflow
Top answer
1 of 4
12

Your approach cannot be used to return the concatenated string: you would return a pointer to a local array that is no longer valid once the function returns, furthermore, you do not check for buffer overflow.

Here is a quick and dirty version that allocates memory:

#include <stdlib.h>  
#include <string.h>

char *concatenate(const char *a, const char *b, const char *c) {
    return strcat(strcat(strcpy(malloc(strlen(a) + strlen(b) + strlen(c) +  1,
                                a), b), c);
}

Here is a more elaborate version using memcpy and testing for malloc failure:

#include <stdlib.h>  
#include <string.h>

char *concatenate(const char *a, const char *b, const char *c) {
    size_t alen = strlen(a);
    size_t blen = strlen(b);
    size_t clen = strlen(c);
    char *res = malloc(alen + blen + clen + 1);
    if (res) {
        memcpy(res, a, alen);
        memcpy(res + alen, b, blen);
        memcpy(res + alen + blen, c, clen + 1);
    }
    return res;
}

It should be more efficient since it does not perform the extra scans strcpy and strcat do, but only careful benchmarking can prove if it is a real improvement over the simple version above.

If you need to concatenate 3 strings into an existing buffer, a very simple solution is:

char dest[DEST_SIZE];

snprintf(dest, sizeof dest, "%s%s%s", a, b, c);

Many systems (linux, GNU, BSD) have an asprintf() function defined that allocates memory for the resulting string:

int asprintf(char **strp, const char *fmt, ...);

Using this function, you can concatenate the three strings quite simply:

#define _GNU_SOURCE
#include <stdio.h>  

char *concatenate(const char *a, const char *b, const char *c) {
    char *p;
    return (asprintf(&p, "%s%s%s", a, b, c) >= 0) ? p : NULL;
}
2 of 4
8

Your str is local to your function.
You could add a fourth parameter to your concatenated string or you could malloc it inside the function, just make sure to free it after use.

char *concatenate(char *a, char *b, char *c)
{
  int size = strlen(a) + strlen(b) + strlen(c) + 1;
  char *str = malloc(size);
  strcpy (str, a);
  strcat (str, b);
  strcat (str, c); 

  return str;
}

int main(void) {

    char *str = concatenate("bla", "ble", "bli");

    printf("%s", str);
    free(str);

    return 0;
}
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ c language โ€บ how-to-concatenate-multiple-strings-in-c
How to Concatenate Multiple Strings in C? - GeeksforGeeks
June 17, 2024 - Input: char str1[50] = "Hello"; char str2[50] = " geeksforgeeks"; Output: Hello geeksforgeeks! To concatenate strings in C, we can use the strcat function from the string.h library.
Discussions

better way to concatenate multiple strings in c? - Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most. Learn more about Collectives ... Is there a better way to concatenate multiple strings together in c other than having multiple calls to strcat() all in a row, like below? More on stackoverflow.com
๐ŸŒ stackoverflow.com
May 4, 2011
How to Concatenate three strings - Post.Byes - Bytes
Another way is to statically allocate a buffer that ought to be big enough and then use strncat() to be sure not to overrun the end of that buffer. If you use strncat(), then be careful with the num argument in successive calls. It needs to decrease as the concatenated string grows. More on post.bytes.com
๐ŸŒ post.bytes.com
April 23, 2019
How do I concatenate two strings in C? - Stack Overflow
How do I add two strings? I tried name = "derp" + "herp";, but I got an error: Expression must have integral or enum type More on stackoverflow.com
๐ŸŒ stackoverflow.com
November 14, 2014
How to concatenate byte strings in Python 3
Python 3.5 will re-introduce some restricted %-formatting, for bytestrings. With Python 3 and the split between str and bytes , one small but important area of programming became slightly more difficult, and much more painful -- wire format protocols https://www.python.org/dev/peps/pep-0461/ More on reddit.com
๐ŸŒ r/Python
7
0
February 28, 2015
Top answer
1 of 16
499

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);
2 of 16
307

Avoid using strcat in C code. The cleanest and, most importantly, the safest way is to use snprintf:

char buf[256];
snprintf(buf, sizeof(buf), "%s%s%s%s", str1, str2, str3, str4);

Some commenters raised an issue that the number of arguments may not match the format string and the code will still compile, but most compilers already issue a warning if this is the case.

๐ŸŒ
Educative
educative.io โ€บ blog โ€บ concatenate-string-c
How to concatenate strings in C: A five-minute guide
The sprintf() function formats data and writes the result into a string buffer. It can concatenate strings while also inserting variables, numbers, or formatted output. Unlike strcat(), sprintf() creates the final string directly instead of ...
๐ŸŒ
DEV Community
dev.to โ€บ educative โ€บ how-to-concatenate-strings-in-c-a-five-minute-guide-o4k
How to concatenate strings in C: a five minute guide - DEV Community
December 21, 2020 - Here are few built-in functions that are available in the string.h header file: ... 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).
๐ŸŒ
StudyMite
studymite.com โ€บ c-programming-language โ€บ examples โ€บ concatenating-strings-in-c
Concatenate strings in C | StudyMite
1 week ago - Using custom loops (without library functions). Using pointers. The simplest and most common way to concatenate strings in C is by using the built-in functions defined in the <string.h> header file: strcat() and strncat().
๐ŸŒ
Post.Byes
post.bytes.com โ€บ home โ€บ forum โ€บ topic
How to Concatenate three strings - Post.Byes - Bytes
April 23, 2019 - You need to use the strcat() function twice. Algorithm: 1) Input 1st string (let it be 'a') 2) Input 2nd string (b) 3) Input third one (c) 4) strcat(a, b) 5) strcat(a, c) strcat(a, b) concatenates a and b and store the resultant string in a.
Find elsewhere
๐ŸŒ
Scaler
scaler.com โ€บ home โ€บ topics โ€บ strings concatenation in c
Strings Concatenation in C - Scaler Topics
April 11, 2024 - String concatenation in C can be simply defined as the addition of two strings or updating them. In C language we can add two or more strings end to end or can update them using the concatenation process. The concatenation helps to combine two or more strings together and provide them as a single string value.
๐ŸŒ
Hero Vired
herovired.com โ€บ learning-hub โ€บ topics โ€บ string-concatenation-in-c
String Concatenation in C : Using strcat() Function
In C language, Appending adds one string to another using the strcat() function. This function concatenates the contents of two strings by attaching the source strings to the end of the destination string to store the result..
๐ŸŒ
Sanfoundry
sanfoundry.com โ€บ c-program-concatenate-strings
String Concatenation in C - Sanfoundry
November 10, 2023 - 2. Call the function str_concat to concatenate the second string to the first string. 3. Allocate memory for the third string as the length of the first string plus the length of the second string.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ methods-to-concatenate-string-in-c-c-with-examples
Methods to concatenate string in C/C++ with Examples - GeeksforGeeks
February 20, 2019 - Here str is the object of std::string class which is an instantiation of the basic_string class template that uses char (i.e., bytes) as its character type. The append function appends the add(variable) string at the end of the init string. ... This is the most easiest method for concatenation of two string.The + operator simply adds the two string and returns a concatenated string.
Top answer
1 of 12
234

C does not have the support for strings that some other languages have. A string in C is just a pointer to an array of char that is terminated by the first null character. There is no string concatenation operator in C.

Use strcat to concatenate two strings. You could use the following function to do it:

#include <stdlib.h>
#include <string.h>

char* concat(const char *s1, const char *s2)
{
    char *result = malloc(strlen(s1) + strlen(s2) + 1); // +1 for the null-terminator
    // in real code you would check for errors in malloc here
    strcpy(result, s1);
    strcat(result, s2);
    return result;
}

This is not the fastest way to do this, but you shouldn't be worrying about that now. Note that the function returns a block of heap allocated memory to the caller and passes on ownership of that memory. It is the responsibility of the caller to free the memory when it is no longer needed.

Call the function like this:

char* s = concat("derp", "herp");
// do things with s
free(s); // deallocate the string

If you did happen to be bothered by performance then you would want to avoid repeatedly scanning the input buffers looking for the null-terminator.

char* concat(const char *s1, const char *s2)
{
    const size_t len1 = strlen(s1);
    const size_t len2 = strlen(s2);
    char *result = malloc(len1 + len2 + 1); // +1 for the null-terminator
    // in real code you would check for errors in malloc here
    memcpy(result, s1, len1);
    memcpy(result + len1, s2, len2 + 1); // +1 to copy the null-terminator
    return result;
}

If you are planning to do a lot of work with strings then you may be better off using a different language that has first class support for strings.

2 of 12
28

I'll assume you need it for one-off things. I'll assume you're a PC developer.

Use the Stack, Luke. Use it everywhere. Don't use malloc / free for small allocations, ever.

#include <string.h>
#include <stdio.h>

#define STR_SIZE 10000

int main()
{
  char s1[] = "oppa";
  char s2[] = "gangnam";
  char s3[] = "style";

  {
    char result[STR_SIZE] = {0};
    snprintf(result, sizeof(result), "%s %s %s", s1, s2, s3);
    printf("%s\n", result);
  }
}

If 10 KB per string won't be enough, add a zero to the size and don't bother, - they'll release their stack memory at the end of the scopes anyway.

๐ŸŒ
Microsoft Learn
learn.microsoft.com โ€บ en-us โ€บ dotnet โ€บ csharp โ€บ how-to โ€บ concatenate-multiple-strings
Concatenate strings in C# - C# | Microsoft Learn
Learn how to combine strings in C# with the + operator, string interpolation, string.Concat, string.Join, and StringBuilder, and how to choose between them.
๐ŸŒ
YouTube
youtube.com โ€บ watch
Concatenating strings in C - YouTube
strcat is a function many of us know. In this video we will not only look at how to use strcat to concatenate strings but also how to safely do so without ru...
Published: April 12, 2020
๐ŸŒ
Aticleworld
aticleworld.com โ€บ home โ€บ how to concatenate two strings in c
How to concatenate two strings in C - Aticleworld
September 21, 2022 - Output: Concatenated String: I Love To Read Aticleworld ยท But the above-mentioned code is not much efficient because in every calling strcat has to walk every character in both the source and destination buffer.
๐ŸŒ
W3Schools
w3schools.com โ€บ c โ€บ ref_string_strcat.php
C string strcat() Function
C Examples C Real-Life Examples C Exercises C Quiz C Code Challenges C Practice Problems C Compiler C Syllabus C Study Plan C Interview Q&A ... The strcat() function appends a copy of one string to the end of another.
๐ŸŒ
TechOnTheNet
techonthenet.com โ€บ c_language โ€บ standard_library_functions โ€บ string_h โ€บ strcat.php
C Language: strcat function (String Concatenation)
Use the strcat function with caution as it is easy to concatenate more bytes into your variable using the strcat function, which can cause unpredictable behavior. In the C Language, the strcat function can be used in the following versions: ... /* Example using strcat by TechOnTheNet.com */ ...
๐ŸŒ
DigitalOcean
digitalocean.com โ€บ community โ€บ tutorials โ€บ string-concatenation-in-c-plus-plus
String Concatenation in C++: 4 Ways To Concatenate Strings | DigitalOcean
August 3, 2022 - Technical tutorials, Q&A, events โ€” This is an inclusive place where developers can find or lend support and discover new ways to contribute to the community.