It all looks good except
Code:
while (*s2 != '\0')
{
*pc = *s1;
pc++;
s1++;
}
Should be
Code:
while (*s2 != '\0')
{
*pc = *s2;
pc++;
s2++;
}
And, while the details of this function may change, the basic idea isn't going to change. This is pretty much 'the' way to concatenate strings. Any other way to do it is really gonna be the same way.
There are two important features about this function that you need to note. First, off, this function changes s1, and second, it assumes that there is enough memory allocated to s1. These still make it a useful function, but to make it work otherwise, you would have to do this...
Code:
// const stops us from changing the strings
char * catstr(const char * s1, const char * s2)
{
char *pc, *result;
result = pc = malloc (strlen(s1) + strlen(s2) + 1);
// I know, we aren't supposed to use string functions, but I
// think this one is okay.
// We have to use two pointers so we have one to walk the
// string, and one to stay at the beginning. This becomes
// important when we have to return something.
// This loop puts the values of s1 into pc.
while (s1 != '\0')
{
*pc = *s1;
pc++
s1++;
}
// This loop puts the values of s2 into pc
while (*s2 != '\0')
{
*pc = *s2;
pc++;
s2++;
}
// Terminate the string.
*pc = '\0';
// pc now points at the end of the string, so we have to use
// result, which still points at the beginning of the string.
return result;
}