strncpy() in C: Copy Part of a String

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.

Syntax Top ↑

strncpy(destination, source, n);

Copy the First Five Characters Top ↑

#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

Limit Copy to the Destination Size Top ↑

#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

Copy into a Structure Member Top ↑

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

strncpy() Is Not Simply a Safer strcpy() Top ↑

  • It may leave the destination without a terminating \0 when truncation occurs.
  • If the source is shorter than n, the remaining destination positions are padded with null bytes.
  • Always design the destination size and termination behavior deliberately.




plus2net.com






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