How to Concatenate Strings in C: Simple Guide with Examples
In C, you concatenate strings using the
strcat function from string.h, which appends one string to another. You must ensure the destination string has enough space to hold the combined result to avoid errors.Syntax
The basic syntax to concatenate strings in C is using the strcat function:
strcat(destination, source);
Here, destination is the string to which source will be appended. The destination must have enough space to hold the combined string including the null terminator.
c
char *strcat(char *destination, const char *source);Example
This example shows how to concatenate two strings safely using strcat. We allocate enough space in the destination array to hold both strings.
c
#include <stdio.h> #include <string.h> int main() { char greeting[50] = "Hello, "; char name[] = "Alice!"; strcat(greeting, name); // Append name to greeting printf("%s\n", greeting); // Output the combined string return 0; }
Output
Hello, Alice!
Common Pitfalls
Common mistakes when concatenating strings in C include:
- Not allocating enough space in the destination string, causing buffer overflow.
- Using uninitialized or non-null-terminated strings.
- Overwriting memory by concatenating to a string literal (which is read-only).
Always ensure the destination array is large enough and properly initialized.
c
#include <stdio.h> #include <string.h> int main() { // Wrong: destination too small char small[5] = "Hi"; char add[] = " there!"; // strcat(small, add); // This causes overflow - unsafe! // Right: allocate enough space char large[20] = "Hi"; strcat(large, add); printf("%s\n", large); return 0; }
Output
Hi there!
Quick Reference
| Function | Description |
|---|---|
| strcat(dest, src) | Appends src string to dest string |
| strcpy(dest, src) | Copies src string to dest string |
| strlen(str) | Returns length of string str |
| Ensure dest has enough space | Prevent buffer overflow errors |
Key Takeaways
Use
strcat to append one string to another in C.Always allocate enough space in the destination string to hold the result.
Never concatenate to string literals; use writable arrays instead.
Initialize strings properly with a null terminator before concatenation.
Check string lengths with
strlen to avoid overflow.