C - strncpy() function
C strncpy() function - copy fixed length string, returning a pointer to the array end
Syntax:
char *strncpy(char *string1, const char *string2, size_t n);
The strncpy() function is used to copy n characters of string2 to string1. If n is less than or equal to the length of string2, a null character (\0) is not appended to the copied string. If n is greater than the length of string2, the string1 result is padded with null characters (\0) up to length n.
Parameters:
Name | Description | Required /Optional |
---|---|---|
string1 | Destination string. | Required |
string2 | Source string. | Required |
n | The number of characters to be copied from source. | Required |
Return value from strncpy()
- The strncpy() function returns a pointer to string1.
Example: strncpy() function
#include <stdio.h>
#include <string.h>
#define SIZE 40
int main(void)
{
char string1[ SIZE ] = "123456789";
char string2[ SIZE ] = "abcdefg";
char string3[ SIZE ] = "123456789";
char string4[ SIZE ] = "abcdefg";
char * return_string;
int n = 2;
printf("Original strings:");
printf("\nString1: %s",string1);
printf("\nString2: %s",string2);
printf("\nn = %d",n);
return_string = strncpy( string1, string2, n);
printf("\nAfter strncpy(string1, string2, n):");
printf("\nString1: %s",string1);
printf("\nString2: %s",string2);
n = 5;
printf("\n\nOriginal strings:");
printf("\nString3: %s",string3);
printf("\nString4: %s",string4);
printf("\nn = %d",n);
return_string = strncpy(string3, string4, n);
printf("\nAfter strncpy(string3, string4, n):");
printf("\nString3: %s",string3);
printf("\nString4: %s",string4);
}
Output:
Original strings: String1: 123456789 String2: abcdefg n = 2 After strncpy(string1, string2, n): String1: ab3456789 String2: abcdefg Original strings: String3: 123456789 String4: abcdefg n = 5 After strncpy(string3, string4, n): String3: abcde6789 String4: abcdefg
C Programming Code Editor:
Previous C Programming: C strcpy()
Next C Programming:C strcspn()
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics