-1

How can I end a string in C? I made a function to connect 2 strings and make one. I read I should end string with '\0' but how to do this with declaration like this?

char* string1= "House";
char* string2= "is big";
ewazdomu
  • 39
  • 5

2 Answers2

1

Create an array big enough to fit both strings plus a single terminator. Copy the first string into the array. Concatenate the other string using strcat.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
1

Try this method

char* concat(const char *s1, const char *s2)
    {
        char *result = malloc(strlen(s1)+strlen(s2)+1);
        strcpy(result, s1);
        strcat(result, s2);
        return result;
    }
Dušan Tichý
  • 498
  • 1
  • 7
  • 21
  • you should always typecast return memory of `malloc` – roottraveller Oct 12 '16 at 08:42
  • 1
    @rootTraveller [I disagree, rather strongly](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc). – unwind Oct 12 '16 at 10:29
  • @unwind yes but `void*` don't get promoted in older version of C. – roottraveller Oct 12 '16 at 10:36
  • @rootTraveller I don't believe that to be true (C89 sure is "older", and does this conversion automatically), but even if it were I disagree with that mattering to how people program today. Requiring code to build on ancient compilers is not normal. – unwind Oct 12 '16 at 11:09