Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Concatenating n characters from source string to destination string in C
In C programming, the strncat() function is used to concatenate a specified number of characters from a source string to the end of a destination string. This function provides more control than strcat() by allowing you to limit the number of characters to be concatenated.
Syntax
char *strncat(char *dest, const char *src, size_t n);
Parameters
- dest − Pointer to the destination string
- src − Pointer to the source string
- n − Maximum number of characters to concatenate
Example 1: Basic strncat() Usage
This example demonstrates concatenating only 4 characters from the source string −
#include <stdio.h>
#include <string.h>
int main() {
char dest[30] = "Hello ";
char src[20] = "Good Morning";
strncat(dest, src, 4);
printf("Concatenated string = %s
", dest);
return 0;
}
Concatenated string = Hello Good
Example 2: Multiple strncat() Operations
This example shows how to perform multiple concatenations with different character counts −
#include <stdio.h>
#include <string.h>
int main() {
char source[] = "TutorialPoint";
char destination[50] = "C ";
/* Truncate destination to 2 characters */
destination[2] = '\0';
/* Concatenate first 2 characters from source */
strncat(destination, source, 2);
/* Concatenate 1 character starting from position 4 */
strncat(destination, &source[4], 1);
printf("The modified destination string: %s
", destination);
return 0;
}
The modified destination string: C Tur
Key Points
- The destination string must have enough space to hold the concatenated result
-
strncat()automatically appends a null terminator after the concatenated characters - The function returns a pointer to the destination string
- Unlike
strcat(),strncat()limits the number of characters copied, preventing buffer overflow
Conclusion
The strncat() function is essential for safe string concatenation in C. It provides precise control over the number of characters to concatenate and helps prevent buffer overflow errors.
Advertisements
