Write the function my_strncat(). The function has three parameters: a char * s1, a const char * s2, and an int max, which represents the maximum size of the s1 buffer. Append the characters in s2 to the end of s1. Make sure you have only one '\0' at the end of the combined characters. Don't go beyond the end of the buffer you are asked to copy to. The function returns a pointer to the first character in s1.

My code does seem to give the right output, but I think the way I declare it wasn't very good,
can someone help me with a better code.

char * my_strncat(char * s1, const char * s2, int max)
    char * p = new char[max];
    for(int i = 0; i < strlen(s1); i++)
        p[i] = s1[i];
    int b = 0;
    for(int i = strlen(s1); i < max; i++)
        p[i] = s2[b];
    s1 = p;
    delete p;
    return s1;

I don't know why your allocating memory because s1 is supposed have enough room to append s2 onto it..

Here's a simple example that came with my help files

           strncat(char *dest, const char *src, size_t n)
               size_t dest_len = strlen(dest);
               size_t i;

               for (i = 0 ; i < n && src[i] != '\0' ; i++)
                   dest[dest_len + i] = src[i];
               dest[dest_len + i] = '\0';

               return dest;

thanks for pointing this out, i am still new to these ideas =.=
could it be possible if you can show me how to do this without array, just merely pointer?

This article has been dead for over six months. Start a new discussion instead.