strncpy in c: 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
C strncpy: 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> #include <conio.h> int main() { char source[100], destination[100]; int charCount; printf("Enter source string\n"); gets(source); printf("Enter number of characters to copy\n"); scanf("%d", &charCount); strncpy(destination, source, charCount); printf("Destination string : %s\n", destination); getch(); return(0); }
Output
Enter source string TechCrashCourse Enter number of characters to copy 7 Destination string : TechCra