In C language, the strncat
function is used to append a specified length of one string to the end of another string. Similar to strcat, it helps avoid buffer overflow issues.
strncat Function Header
The header file for the strncat
function is <string.h>
. Before using the strncat
function, ensure that this header file is included in your C code:
#include <string.h>
strncat Function Prototype
char *strncat(char * restrict s1,
const char * restrict s2,
size_t n);
The strncat
function appends up to n
characters from the string pointed to by s2
to the end of the string pointed to by s1
. The initial character of s2
will overwrite the null character at the end of s1
. The null terminator '\0'
is always appended to the result. If copying occurs between overlapping objects, the behavior is undefined.
Parameter Description
s1
: Pointer to the destination string, representing the modified string. It must have enough space to accommodate the appended content;s2
: Pointer to the source string, representing the string to be appended;n
: Indicates the maximum number of characters to append froms2
;
Return Value
The strncat
function returns a pointer to the destination string, which is the value of s1
;
strncat Example Code
Example 1:
#include <stdio.h>
#include <string.h>
int main() {
char s1[50] = "Hello, ";
char s2[] = "World!";
strncat(s1, s2, 3); // Append 3 characters
printf("%s\n", s1);
return 0;
}
Program Output
Hello, Wor
Example 2:
Appending stops when a null terminator is encountered;
#include <stdio.h>
#include <string.h>
int main() {
char s1[50] = "Hello, ";
char s2[] = "W\0orld!";
strncat(s1, s2, 3);
printf("%s\n", s1);
return 0;
}
Program Output
Hello, W