Q: how to merge two strings using c? #include<stdio.h>

/* a function to merge two strings */

void stringMerge(char* f, char* s){

while(*f++);

while((*f++ = *s++));

}

int main(){

char s1[] = "Hello ";

char s2[] = "World";

stringMerge(s1,s2);

printf("%s",s1);

return 0;

}


A: Taking into account the declarations of strings that you are going to concatenate then it seems you mean the following function implementation.
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

char * stringMerge(const char *s1, const char *s2)
{
    size_t n = strlen(s1);

    char *p = (char *)malloc(n + strlen(s2) + 1);

    if (p)
    {
        strcpy(p, s1);
        strcpy(p + n, s2);
    }

    return p;
}


int main( void )
{
    char s1[] = "Hello ";
    char s2[] = "World";

    char *p = stringMerge(s1, s2);

    puts(p);

    free(p);
}

Or the following
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

char * stringMerge(const char *s1, const char *s2)
{
    size_t n = strlen(s1);

    char *p = (char *)malloc(n + strlen(s2) + 1);

    if (p)
    {
        char *t = p;
        while (*t = *s1++) ++t;
        do { *t = *s2++; } while (*t++);
    }

    return p;
}

int main( void )
{
    char s1[] = "Hello ";
    char s2[] = "World";

    char *p = stringMerge(s1, s2);

    puts(p);

    free(p);
}

In the both programs the output is
Hello World


A: I suggest you to use the strncat() from string.h. Here is your code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void){
    char *s1 = "Hello ";
    char *s2 = "World\n";
    size_t s1_size = strlen(s1);
    size_t s2_size = strlen(s2);
    char *concat = calloc((s1_size + 1 + s2_size + 1), sizeof(char));
    if (concat == NULL) {
        perror("Calloc");
        exit(EXIT_FAILURE);
    }
    strncat(concat, s1, s1_size);
    strncat(concat, s2, s2_size);
    printf("%s", concat);
    free(concat);
    return 0;

}

