#include <stdio.h>
#include <string.h>
int main(void){
char var1[20]="First one";
char var2[]="Second two";
strncpy(var2,var1,5);
printf(var2);
return 0;
}
The output of above code is here, ( first 5 chars of var1 variable is copied to var2 variable )
Firstd two
We can use string function strncpy()
to copy part strings. strcpy(destination_string, source_string, n);
#include <stdio.h>
#include <string.h>
int main() {
char dest[6];
strncpy(dest, "hello", 5);
dest[5] = '\0'; // Manually adding null-termination
printf("%s", dest); // Output: hello
}
Using strncpy() may result in non-null terminated destination strings if the source string is longer than the number of characters to copy. It’s essential to manually terminate the destination string.
#include <stdio.h>
#include <string.h>
int main() {
char src[] = "plus2net tutorials";
char dest[10];
strncpy(dest, src, 9);
dest[9] = '\0'; // Ensure null-termination
printf("Destination: %s\n", dest);
return 0;
}
Output:
Destination: plus2net
Use strncpy() to avoid buffer overflows when dealing with user input or unknown string lengths.
#include <stdio.h>
#include <string.h>
int main() {
char src[] = "Very long input string";
char dest[10];
strncpy(dest, src, sizeof(dest) - 1);
dest[sizeof(dest) - 1] = '\0'; // Prevent overflow
printf("Safely copied string: %s\n", dest);
return 0;
}
Output:
Safely copied string: Very long
strncpy() is useful when copying strings into struct members.
#include <stdio.h>
#include <string.h>
struct Student {
char name[20];
int age;
};
int main() {
struct Student student;
char input[] = "Alice Wonderland";
strncpy(student.name, input, sizeof(student.name) - 1);
student.name[sizeof(student.name) - 1] = '\0'; // Ensure null-termination
student.age = 20;
printf("Name: %s, Age: %d\n", student.name, student.age);
return 0;
}
Output:
Name: Alice Wonderlan, Age: 20