The strncpy()
function is used to copy characters from the source string to the destination string. The count of the specified characters is provided as a parameter to the strncpy() function. If the source string is more than copied character count it is padded with zeros until the total number of characters.
strncpy() Function Syntax
The syntax of the strncpy() function is like below.
strncpy(SOURCE,DESTINATION,NUMBER)
- SOURCE is the source string where specified number of characters will be copied.
- DESTINATION is the destination string where specified number of characters will be copied.
- NUMBER is the number of characters copied from SOURCE to DESTIONATION.
Copy From Source To Destination String
In the following example, we will copy the string from the specified source to the destination. We will also specify the number of characters we cant to copy. The source string is “wisetut.com” and we will copy the first 7 characters of this string.
#include <stdio.h>
#include <string.h>
int main ()
{
char source[]= "wisetut.com";
char destination[10];
strncpy ( source,destination, 7 );
puts (destination);
return 0;
}
Copy All Characters of Source String To Destination
In this example, we will copy all characters of the source string to the destination string. We will use the sizeof()
function in order to decide the source string character count and provide for the strncpy() function.
#include <stdio.h>
#include <string.h>
int main ()
{
char source[]= "wisetut.com";
char destination[13];
strncpy ( source,destination, sizeof(source) );
puts (destination);
return 0;
}