krrishna
krrishna

Reputation: 2078

how to merge two strings

I have the following program which fails to merge the two strings because the string1 does not have enough space to hold the merged string .When string1 doesnt have enough space and without using the additional array to hold merged string how to return a merged string ?

 #include<stdio.h>
 #include<string.h>
 int main()
  { 
      void strcat2(char *str1,char *str2);
      strcat2("john","kris");
      getchar();
  }
  void strcat2(char *str1,char *str2)
   {
     for (; *str1++;);
     for (;*str1++ =*str2++;);

  }

Upvotes: 0

Views: 302

Answers (2)

Rahul Tripathi
Rahul Tripathi

Reputation: 172488

You can try this as this is a better one or just allocate more space.:-

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

char* concat(const char *s1, const char *s2)
{
    char *result = malloc(strlen(s1)+strlen(s2)+1);

    strcpy(result, s1);
    strcat(result, s2);
    return result;
}

Upvotes: 3

Lee Daniel Crocker
Lee Daniel Crocker

Reputation: 13171

In C, you have to do your own memory allocation. That means that in general it is not possible for functions to return strings in the way garbage collected languages can. When you need to return a string from a function, you must either pass in the result string, pre-allocated by the caller, or else allocate it dynamically and rely on the caller to free it.

There's no shortcut in C, you just have to do the work.

Upvotes: 2

Related Questions