I'm trying to make a function similar to strcat(char,char) in string.h header file. Somehow this code does not catenate the strings. Please help me make it better.

void strappend(char *a, char *b)
    int i;
      int start_pos = strlen(a);
    for (i=0; b[i]!='\0'; i++)
        a[start_pos + i] = b[i];
      a[i] = '\0';

Thanks in advance!

Edited by deceptikon: Restored the original post. Please don't delete your post's content, it destroys the continuity of the thread and ensures that *nobody* will benefit from it in the future.

5 Years
Discussion Span
Last Post by nmakes

How much space have you allocated for the string a? What happens if a can hold, say, four characters, and then you try to write an extra 10 characters from b after the end of it? Something bad happens. Don't forget to allow for such things.

Let's ignore that for a moment. Let's imagine that you have a string of size ten, a, and a string of size ten, b. Then your code starts concatenating. What is the value of i when the code finds the end of string b? 10. So where do you write the '\0'?

a[i] = '\0';
At a[10]. Is that the end of the new, concatentaed string? No, it is not.

Edited by Moschops

Votes + Comments

Yeah.. I solved it the next moment I posted this one. Actually in the last line I had to write a[start_pos + i] = '\0'; and not a[i] = '\0';
Anyway, thanks! :D

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.