C++ strncpy()

Learn via video course
FREE
View all courses
C++ Course: Learn the Essentials
C++ Course: Learn the Essentials
by Prateek Narang
1000
5
Start Learning
C++ Course: Learn the Essentials
C++ Course: Learn the Essentials
by Prateek Narang
1000
5
Start Learning
Topics Covered

strncpy() in C++ copies the first n characters of the source to the destination. In the case of a count less than the length of the source, strncpy() in C++ copied the first count characters over to the destination and it is not null-terminated. In cases where the count exceeds the source, strncpy() in C++ copies all the characters from the source to the destination. In addition, terminating null characters are added to the destination until the total number of characters equals the count.

Syntax of strncpy() in C++.

Parameters of strncpy() in C++

dest − A pointer that points to the destination array where the content will be copied.

src − This is the string to be copied.

n − This is the number of characters that must be copied from the source.

Return value of strncpy() in C++

strncpy() in C++ returns the pointer to the copied string.

What is strncpy() in C++ and how does strncpy() function works?

What is strncpy() in C++

strncpy() in C++ copies up to n characters from the string pointed to by src to the string pointed to by dest.

There can be two cases depending on the value of n and the length of the source.

The strncpy() in C++ checks for the value of n, and according to the value of n, the strncpy() copies the characters from the source to the destination.

How does strncpy() in C++ works

If the length of the source is less than n i.e., there are not enough characters to be copied then, null bytes will be added to the remainder of dest. If the source is longer than num, i.e., n characters can be copied from the length of the source, then no null character is appended to the destination.

Examples

  • When the count is less than the length of the src

Output

  • When count is more than length of src

Output

Conclusion

  • strncpy() in C++ copies the first n characters of the source to the destination.

  • There can be two cases depending on the value of n and the length of the source.

  • If the length of the source is less than n - strncpy() in C++ copies all the characters from the source to the destination. In addition, terminating null characters are added to the destination until the total number of characters equals the count.

  • If the length of the source is greater than n - strncpy() in C++ copies the first n characters to the destination, not null-terminated.