strncpy() in C - Source Code Example

In this source code example, we will see how to use the strncpy() function in C programming with an example.

strncpy() Function Overview

The strncpy() function is a part of the C programming language's standard library and is defined in <string.h>. It is used to copy a specified number of characters from one string to another. 

Here are some key points: 

1. Copies up to n characters from the source string to the destination string. 

2. If the source string is shorter than n characters, the function pads the destination string with null bytes. 

3. If there is no null byte in the first n characters of the source string, the destination string won't be null-terminated. Always ensure proper termination when using strncpy()

4. While strncpy() can prevent buffer overflows by limiting the number of characters copied, care should still be taken to ensure that the destination buffer is large enough to hold the number of characters specified by n, plus the null terminator.

Source Code Example

#include <stdio.h>
#include <string.h>

int main() {
    char src[] = "C Programming is fun!";
    char dest1[25];
    char dest2[7];

    // Full copy
    strncpy(dest1, src, sizeof(dest1));
    dest1[sizeof(dest1) - 1] = '\0'; // Ensuring null termination
    printf("Full Copy: %s\n", dest1);

    // Partial copy
    strncpy(dest2, src, 6);
    dest2[6] = '\0'; // Ensuring null termination
    printf("Partial Copy (6 characters): %s\n", dest2);

    // Example where source is shorter than n
    char shortSrc[] = "Hello";
    char dest3[10];
    strncpy(dest3, shortSrc, sizeof(dest3));
    printf("Short Source Copy: %s\n", dest3);

    return 0;
}

Output

Full Copy: C Programming is fun!
Partial Copy (6 characters): C Prog
Short Source Copy: Hello

Explanation

1. The first example copies the entire string from src to dest1 and ensures that the destination string is null-terminated.

2. The second example demonstrates a partial copy where only the first 6 characters of src are copied to dest2.

3. The third example shows a scenario where the source string "Hello" is shorter than the size of dest3. After copying, the remaining positions in dest3 are filled with null bytes.


Comments