Understanding strcat()
in C
The strcat()
function in C is used to concatenate (append) one string to another. It is declared in the <string.h>
library.
Syntax
char *strcat(char *destination, const char *source);
destination
: The string to whichsource
will be appended.source
: The string to be appended todestination
.- Returns: A pointer to the
destination
string.
Important Notes:
- The
destination
string must have enough space to accommodate the concatenated result. strcat()
modifiesdestination
in place.- The
source
string remains unchanged.
Example 1: Basic Usage
#include <stdio.h>
#include <string.h>
int main() {
char str1[20] = "Hello, ";
char str2[] = "World!";
strcat(str1, str2); // Appends str2 to str1
printf("Concatenated String: %s\n", str1);
return 0;
}
Output:
Concatenated String: Hello, World!
Example 2: Concatenating Multiple Strings
#include <stdio.h>
#include <string.h>
int main() {
char str[50] = "Welcome";
strcat(str, " to ");
strcat(str, "C Programming!");
printf("%s\n", str);
return 0;
}
Output:
Welcome to C Programming!
Example 3: Buffer Overflow Risk
#include <stdio.h>
#include <string.h>
int main() {
char str1[10] = "Hi";
char str2[] = " there!";
strcat(str1, str2); // Risk: str1 may not have enough space!
printf("%s\n", str1);
return 0;
}
Potential Issue:
- If
str1
does not have enough space, buffer overflow occurs, which can lead to crashes or unexpected behavior.
Safe Alternative: strncat()
To avoid buffer overflow, use strncat()
:
strncat(destination, source, n);
- Ensures that only
n
characters are appended.
Example:
#include <stdio.h>
#include <string.h>
int main() {
char str1[10] = "Hi";
char str2[] = " there!";
strncat(str1, str2, sizeof(str1) - strlen(str1) - 1);
printf("%s\n", str1);
return 0;
}
Key Takeaways
✔ strcat()
is used to append one string to another.
✔ The destination array must have enough space to hold the concatenated string.
✔ Use strncat()
to prevent buffer overflow.
Would you like a deeper explanation or custom examples