In the C Programming Language, the strncpy characteristic copies the first n characters of the array pointed to through s2 into the array pointed to through s1. It returns a pointer to the destination.
If the strncpy function encounters a null personality in s2, the function will add null characters to s1 till n characters have been written.
Syntax
The syntax for the strncpy characteristic in the C Language is:
char *strncpy(char *s1, const char *s2, size_t n);
Parameters or Arguments
s1 An array where s2 will be copied to. s2 The string to be copied. n The range of characters to copy.
Returns
The strncpy function returns s1.
Required Header
In the C Language, the required header for the strncpy function is:
#include <string.h>
Applies To
In the C Language, the strncpy function can be used in the following versions:
ANSI/ISO 9899-1990
strncpy Example
Let’s appear at an instance to see how you would use the strncpy function in a C program:
/* Example using strncpy by TechOnTheNet.com */
#include <stdio.h>
#include <string.h>
int main(int argc, const char * argv[])
{
/* Create an example variable capable of holding 50 characters */
char example[50];
/* Copy 16 characters into the example variable
from the string "TechOnTheNet.com knows strncpy" */
strncpy (example, "TechOnTheNet.com knows strncpy!", 16);
/* Add the required NULL to terminate the copied string */
/* strncpy does not do this for you! */
example[16] = '\0';
/* Display the contents of the example variable to the screen */
printf("%s\n", example);
return 0;
}
When compiled and run, this utility will output:
TechOnTheNet.com
Similar Functions
Other C functions that are comparable to the strncpy function:
memcpy feature memmove characteristic strcpy characteristic
Leave a Review