How to Use strcat in C: Syntax, Example, and Tips
In C, use
strcat to join two strings by appending the second string to the first. Make sure the first string has enough space to hold the combined result, and include #include <string.h> to use strcat.Syntax
The strcat function appends the source string to the end of the destination string. The syntax is:
char *strcat(char *dest, const char *src);
dest: The string to which src will be appended. It must have enough space.
src: The string to append to dest.
The function returns a pointer to dest.
c
char *strcat(char *dest, const char *src);Example
This example shows how to join two strings using strcat. The first string has enough space to hold both strings combined.
c
#include <stdio.h> #include <string.h> int main() { char greeting[20] = "Hello, "; char name[] = "Alice!"; strcat(greeting, name); printf("%s\n", greeting); return 0; }
Output
Hello, Alice!
Common Pitfalls
Common mistakes when using strcat include:
- Not allocating enough space in the destination string, causing buffer overflow.
- Using uninitialized destination strings.
- Forgetting to include
<string.h>.
Always ensure the destination array is large enough to hold the combined string plus the null terminator.
c
#include <stdio.h> #include <string.h> int main() { char dest[10] = "Hi"; char src[] = " there!"; // Wrong: dest may not have enough space // strcat(dest, src); // This can cause overflow // Right: use a bigger array char safe_dest[20] = "Hi"; strcat(safe_dest, src); printf("%s\n", safe_dest); return 0; }
Output
Hi there!
Quick Reference
- Include:
<string.h> - Function:
strcat(dest, src) - Returns: Pointer to
dest - Important:
destmust have enough space for the result
Key Takeaways
Always include to use strcat in C.
Ensure the destination string has enough space to hold the combined result.
strcat appends the source string to the end of the destination string.
Using strcat on insufficiently sized arrays causes buffer overflow and bugs.
The function returns the destination string pointer.