The C strncpy function is a String Function, which used to copy n number of characters from one string to another. The syntax of the strncpy in C Programming language is
char *strncpy(char *destination, char *source, size_t n);
or we can simply write it as:
strncpy(str1, str2, string_size);
- source: A valid string
- destination: This is where the function will copy the characters from Source.
- n: The number of characters that you want to copy from Source.
strncpy in C Example
The strncpy function used to copy the user-specified string. This program will help you to understand the strncpy with multiple examples.
TIP: You have to include the #include<string.h> header before using this strncpy String Function.
/* strncpy in C Programming to copy string */ #include <stdio.h> #include<string.h> int main() { char str1[50], str2[50], str4[50]; char str3[] = "C Programming Language "; strncpy(str1, str3, 40); printf("\n The Final String after Copying = %s", str1); strncpy(str2, str3, 9); printf("\n The Final String after Copying = %s", str2); memset(str4, '\0', sizeof(str4)); strncpy(str4, "Tutorial Gateway", 16); printf("\n The Final String after Copying = %s", str4); }
OUTPUT
ANALYSIS
It will copy all the characters in str3 to str1 because the length of C Programming Language is less than the given size 40.
strncpy(str1, str3, 40);
It will copy the first 9 characters present in str3 to str1 because we are restricting the size to 9.
strncpy(str2, str3, 9);
strncpy in C Example 2
This program allows the user to enter his/her own string. Next, it is going to use the strncpy function to copy the user-specified string.
/* strncpy in C Programming to copy string */ #include <stdio.h> #include<string.h> int main() { char str1[100], str2[100]; printf("\n Please Enter the String that you want to Copy : "); gets(str2); //memset(str1, '\0', sizeof(str1)); strncpy(str1, str2, 7); printf("\n The Final String after Copying = %s", str1); }
OUTPUT
Although the given string is a valid one, strncpy function only copied up to Learn C. This is because we restricted the copy function to the first 7 characters (including spaces).
Let me change the Size value, and see