strncpy(): Copying part of strings in C

#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.
Part of the second string is added to the first string.
strcpy(destination_string, source_string, n);
  • Source string is not affected
  • Destination string is replaced by source string.

Example: Ensuring Null-Termination

#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
}

Handling Non-Null Terminated Strings

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

Example: Preventing Buffer Overflow

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

Using strncpy() with Structs

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


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com



    Post your comments , suggestion , error , requirements etc here




    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer