![]() |
VOOZH | about |
In C/C++, strncat() is a predefined function used for string handling. string.h is the header file required for string functions.
This function appends not more than n characters from the string pointed to by src to the end of the string pointed to by dest plus a terminating Null-character. The initial character of the string(src) overwrites the Null-character present at the end of a string(dest). Thus, the length of the string(dest) becomes strlen(dest)+n. But, if the length of the string(src) is less than n, only the content up to the terminating null-character is copied and the length of the string(dest) becomes strlen(src) + strlen(dest).
The behavior is undefined if -
Syntax:
char *strncat(char *dest, const char *src, size_t n)
Parameters: This method accepts the following parameters:
Return Value: The strncat() function shall return the pointer to the string(dest).
Application
Given two strings src and dest in C++, we need to append 'n' character from src to dest, let's say n=5.
Examples:
Input: src = "world" dest = "Hello " Output: "Hello world" Input: src = "efghijkl" dest = "abcd" Output: "abcdefghi"
Program:
Output:
Source string : efghijkl Destination string : abcdefghi
How strncat() is different from strcat() ?
It is recommended by many of the programmers that strncat() is safe as compared to strcat() because strcat() does not check for the size of the copied data, and copies until it gets to a null terminator, it might cause a buffer overflow while strncat() check for the size of the copied data, and will copy only 'n' bytes.
Output:
Before strcat() function execution, destination string : geeks After strcat() function execution, destination string : geeksforgeeks Before strncat() function execution, destination string : geeks After strncat() function execution, destination string : geeksfor