Basic Usage
The strncpy() function is similar to the strcpy() function. However, unlike strcpy(), it copies a specified number of characters from the source string to the destination string.
The strncpy() syntax is as:
Function Parameters
The strncpy() function accepts 3 parameters:
- dest – This is a pointer to a character array where the set characters are stored after copy.
- src – This pointer points to the character array from where the specified character arrays are copied.
- n – the maximum number of characters to copy from the src string.
The function copies the number of characters specified by n from the src to the memory pointed by dest.
If the function receives the value of n less than the length of the src array, it copies the specified n characters without a null terminating character.
If n is more than the length of the src array, it copies all the n characters with a null-terminated character to dest.
Function Return Value
The function returns a pointer to the dest array.
Example 1
The following example illustrates how to use the strncpy() function.
#include <string.h>
int main() {
char src[] = "Hello, world!";
char dest[20];
strncpy(dest, src, sizeof(dest));
printf("Copied string: %s \n", dest);
return 0;
}
In the above example program, we specify the source string with the value: “Hello, world!”. We then proceed to define the destination string and use the strncpy() function to copy the size of the source string.
The output from the above program is as shown:
Example 2
The essence of the next example is to illustrate how to copy partial characters from the source string. For example, to copy the first 5 characters, we can do:
#include <string.h>
int main() {
char src[] = "Hello, world!";
char dest[20];
strncpy(dest, src, 5);
printf("Partial string: %s \n", dest);
return 0;
In the example program above, we only copy 5 bytes from the source string. Since the value of n is less than the length of the source string. The destination string is not null terminated.
Example 3
We can add a null terminating character manually as shown in the example program below:
#include <string.h>
int main() {
char src[] = "Hello, world";
char dest[10];
strncpy(dest, src, 5);
dest[5] = '\0';
return 0;
}
In the example above, we manually add a null terminating character after copying the target number of bytes from the source string
Example 4
If you pass the value of n greater than the size of the source string, the strncpy() function copies all the characters in from the source string and adds a series of null-terminating characters for the remaining bytes.
#include <string.h>
int main() {
char src[] = "Hello, world";
char dest[20];
strncpy(dest, src, sizeof(src)+5);
printf("Destination %s \n", dest);
return 0;
}
Conclusion
In this tutorial, we discussed how to use the strncpy() function in C. Using this function, you can copy specific number of characters from a string to a destination string.
from https://ift.tt/3DlcOcm

0 Comments