strncat() Function
The strncat()
function in C appends a specified portion of one string to the end of another, ensuring the resulting string is null-terminated. It is useful for safely concatenating strings while limiting the number of characters appended, which helps prevent buffer overflow issues.
Syntax of strncat()
char *strncat(char *destination, const char *source, size_t num);
Parameters
Parameter | Description |
---|---|
destination | Pointer to the destination array which should contain a null-terminated C string and be large enough to hold the concatenated result, including the extra null-character. |
source | C string to be appended to the destination. |
num | Maximum number of characters to append from the source. |
Return Value
The function returns a pointer to the destination string.
If the source string is shorter than the specified limit, only the characters up to the null terminator are appended. This function always ensures that the final string is null-terminated.
Examples for strncat()
Example 1: Basic String Concatenation
This example demonstrates how to append a portion of one string to another using strncat()
.
Program
#include <stdio.h>
#include <string.h>
int main() {
char dest[30] = "Hello";
char src[] = ", World!";
// Append first 7 characters from src to dest
strncat(dest, src, 7);
printf("Concatenated string: %s\n", dest);
return 0;
}
Explanation:
- The destination string initially contains “Hello”.
- The source string contains “, World!”, and the first 7 characters (“, Worl”) are appended.
- The resulting string is null-terminated and printed.
Output:
Concatenated string: Hello, Worl
Example 2: Appending a Shorter String
This example shows how strncat()
handles a case where the source string is shorter than the specified limit.
Program
#include <stdio.h>
#include <string.h>
int main() {
char dest[20] = "Test";
char src[] = "123";
// Attempt to append 5 characters from src to dest
strncat(dest, src, 5);
printf("Concatenated string: %s\n", dest);
return 0;
}
Explanation:
- The destination string starts as “Test”.
- The source string “123” has fewer characters than the specified limit, so the entire source is appended.
- The resulting string “Test123” is null-terminated and printed.
Output:
Concatenated string: Test123
Example 3: Concatenating with Preexisting Content
This example demonstrates concatenating additional text to a string that already contains content.
Program
#include <stdio.h>
#include <string.h>
int main() {
char dest[50] = "Data:";
char src[] = " Example usage";
// Append up to 10 characters from src to dest
strncat(dest, src, 10);
printf("Concatenated string: %s\n", dest);
return 0;
}
Explanation:
- The destination string starts with “Data:”.
- The source string ” Example usage” has extra text, but only the first 10 characters (” Example u”) are appended.
- The resulting string “Data: Example u” is null-terminated and printed.
Output:
Concatenated string: Data: Example u