strncat

The strncat function copies the content of a source string at the end of a destination string. Different from the strcat function, however, it checks if there is enough space available in the destination buffer before it appends characters. This makes the strncat function much safer to use than strcat.

The strncat function requires three arguments. The first argument is a pointer to the destination string. The second argument is a pointer to the source string (the one that will be copied). The third argument is an integer value which determines how many characters will be copied from the source to the destination string. This value should be calculated to allow for enough space in the buffer pointed by the first argument.

Another difference between strcat and strncat is that strncat will always copy a null character at the end of the destination string, even if the size of the source is greater than the number of characters allowed.

The following code shows an example of strncat in use:

#include <stdio.h>       
#include <string.h>       

int main()
{
        char *src = "source string";
        // destination string
        char dest[50] = "beginning of "; 
        // (notice that it must have enough space
                                         
        strncat(dest, src, 5);
        printf("the destination string is "
               " now '%s'\n", dest);
        return 0;
}

This will result in the following output:

the destination string is now 'beginning of sourc'
Tags: strncat, standard, C
Article created on 2008-08-19 22:17:18

Post a comment