C strncpy() library function

The function char *strncpy(char *destination, const char *source, size_t n); copies the first n characters from the string pointed by source to string pointed by destination. If the length of source string is less than n, then destination string is padded with zeros until a total of n characters have been written into it.

Function prototype of strncpy

char *strncpy(char *destination, const char *source, size_t n);

Return value of strncpy

  • destination : This is pointer to a string where the content is to be copied.
  • source : This is pointer to a string from where data to be copied.
  • n : Number of characters to be copied from source.

C program using strncpy function

The following program shows the use of strncpy function to copy n characters from a string into another string.

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

int main()
   char source[100], destination[100];
   int charCount;
   printf("Enter source string\n");
   printf("Enter number of characters to copy\n");
   scanf("%d", &charCount);
   strncpy(destination, source, charCount);
   printf("Destination string : %s\n", destination);

Enter source string
Enter number of characters to copy
Destination string : TechCra