C Library Functions -strncpy()
C Standard Library - <string.h>
Description
C Library Functionschar *strncpy(char *dest, const char *src, size_t n)holdsrccopies the string pointed to bydest, copy at mostncharacters. When the length of src is less than n, the remaining part of dest will be filled with null bytes.
Declaration
Below is the declaration of the strncpy() function.
char *strncpy(char *dest, const char *src, size_t n)
Parameter
- dest-- Points to the destination array used to store the copied content.
- src-- the string to be copied.
- n-- the number of characters to be copied from the source.
Return Value
The function returns the final copied string.
Example
The following example demonstrates the usage of the strncpy() function. Here, we use the memset() function to clear memory locations.
Example
#include <stdio.h>
#include <string.h>
int main()
{
char src[40];
char dest[12];
memset(dest, '\0', sizeof(dest));
strcpy(src, "This is example.com");
strncpy(dest, src, 10);
printf("The final target string: %s\n", dest);
return(0);
}
Let us compile and run the above program, which will produce the following result:
最终的目标字符串: This is ruother extensions