How to concatenate two strings in C?

Question:

When executing code

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

int main() {
    char *first = "first";
    char *second = "second";
    char *third = strcat(first, second);
}

a segmentation error occurs.

Answer:

If the contents of the lines are known at the compilation stage, then gluing can be organized at the compilation stage

#define FIRST  "first"
#define SECOND "second"

int main(void) 
{
    const char *first  = FIRST;
    const char *second = SECOND;
    const char *third  = FIRST SECOND;
}

But that really depends on what you need.

For run-time concatenation, using the strcat function is not a good idea, due to the fact that with each concatenation, the function scans the already constructed part of the string over and over again. (For this reason, strcat is actually a useless function.) It's better to use the usual snprintf for this purpose.

#include <stdio.h>

int main(void) 
{
    const char *first  = "first";
    const char *second = "second";

    char third[512];
    snprintf(third, sizeof third, "%s%s", first, second);
}

Which method of reserving memory for the destination string is best for you depends on your specific circumstances and requirements.

Scroll to Top