strncpy() copies at most n characters from a source string to a destination array. If the source is at least n characters long, the destination is not automatically null-terminated.
strncpy(destination, source, n);
#include <stdio.h>
#include <string.h>
int main(void) {
char source[] = "First one";
char destination[6];
strncpy(destination, source, 5);
destination[5] = '\0';
printf("%s\n", destination);
return 0;
}
Output
First
#include <stdio.h>
#include <string.h>
int main(void) {
char source[] = "Very long input string";
char destination[10];
strncpy(destination, source, sizeof(destination) - 1);
destination[sizeof(destination) - 1] = '\0';
printf("%s\n", destination);
return 0;
}
Output
Very long
#include <stdio.h>
#include <string.h>
struct Student {
char name[20];
int age;
};
int main(void) {
struct Student student;
char input[] = "Alice Wonderland";
strncpy(student.name, input, sizeof(student.name) - 1);
student.name[sizeof(student.name) - 1] = '\0';
student.age = 20;
printf("Name: %s, Age: %d\n", student.name, student.age);
return 0;
}
\0 when truncation occurs.n, the remaining destination positions are padded with null bytes.Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.