strncpy

The strncpy function copies the content of a string into another string. Different from the strcpy function, however, it checks the size of the buffer passed as a parameter, and copies only the number of elements that can be correctly stored.

The strncpy function requires three arguments. The first argument is a pointer to the destination string (the buffer). The second argument is a pointer to the source string.The third argument is the size of the buffer passed in the first argument.

The following code shows an example of strncpy use:

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

int main()
{
        char *src = "source string";
        char dest[50]; // destination string
        char dest2[5]; // another destination string
        strncpy(dest, src, 50);
        printf("the result string is '%s'\n", dest);
        strncpy(dest2, src, 5);
        printf("the result string is now '%s'\n", dest2);
        return 0;
}

This example will print the following result:

the result string is 'source string'
the result string is now 'sourc'
Article created on 2008-08-19 22:19:00

Post a comment