VOOZH about

URL: https://www.geeksforgeeks.org/c/strncpy-function-in-c/

⇱ strncpy() Function in C - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

strncpy() Function in C

Last Updated : 5 Aug, 2024

The strncpy() function in C is a predefined function in the string.h library used to copy a specified number of characters from one string to another. To use this function, we must include the <string.h> header file in our program. It copies up to n characters from the source string to the destination string and works with char data types.

Syntax of strncpy() in C

char *strncpy(char *dest, const char *src, size_t n);

Parameters of strncpy()

The strncpy(dest, src, n) function takes three parameters:

  • dest: A pointer to the destination array where the content is to be copied.
  • src: A pointer to the source string to be copied.
  • n: The number of characters to be copied from the source string.

Return Value of strncpy()

The strncpy(dest, src, n) function returns a pointer to the destination string dest. If the length of src is less than n, the remainder of dest will be padded with null characters.

Examples of strncpy() in C

Input:
char src[] = "Hello, World!";
char dest[20];

Output:
Destination string: Hello //Copied first 5 characters from src to dest

The below examples demonstrates the usage of strncpy() in different scenarios in C language.

Example 1

The below program demonstrates the basic usage of the strncpy() function to copy a specified number of characters from one string to another.


Output
Destination string: Hello

Time Complexity: O(n), where n is the number of characters to be copied.
Auxiliary Space: O(1)

Example 2

The below example demonstrates how we can use strncpy() to copy a fixed length of characters from a source string to a destination string, ensuring the destination string is properly null-terminated.


Output
Custom copied string: Programming in 

Time Complexity: O(n), where n is the number of characters to be copied.
Auxiliary Space: O(1)

Example 3

The below example demonstrates how to use strncpy() to copy a fixed-length substring from the source string into the destination string.


Output
Fixed-length substring: Moore

Time Complexity: O(n), where n is the number of characters to be copied.
Auxiliary Space: O(1)

Points to Remember

  • The strncpy() function does not null-terminate the destination string if the length of src is greater than or equal to n. Therefore, it is important to manually null-terminate the destination string.
  • If src is shorter than n, the remainder of dest will be padded with null characters, ensuring the destination string is properly null-terminated.
Comment
Article Tags: