Easy Tutorial
❮ C Function Memchr C Standard Library Locale H ❯

C Library Function - strncpy()

C Standard Library - <string.h>

Description

The C library function char *strncpy(char *dest, const char *src, size_t n) copies up to n characters from the string pointed to by src to dest. If the length of src is less than n, the remainder of dest will be padded with null bytes.

Declaration

Here is the declaration for the strncpy() function.

char *strncpy(char *dest, const char *src, size_t n)

Parameters

Return Value

This function returns the final copied string.

Example

The following example demonstrates the use of the strncpy() function. Here, we use the memset() function to clear memory locations.

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

int main()
{
   char src[40];
   char dest[12];

   memset(dest, '\0', sizeof(dest));
   strcpy(src, "This is tutorialpro.org");
   strncpy(dest, src, 10);

   printf("Final destination string: %s\n", dest);

   return(0);
}

Let's compile and run the above program, which will produce the following result:

Final destination string: This is ru

C Standard Library - <string.h>

❮ C Function Memchr C Standard Library Locale H ❯