- How to concatenate two strings using a user-defined function
- How to move a pointer to the null character of a string
- How to copy characters from one string to another using pointers
- Why the destination array must be large enough to hold both strings
- How to add the terminating null character after concatenation
- How this manual method relates to the standard
strcat()function
How Pointer-Based String Concatenation Works
Concatenation means joining two strings end to end. For example, if the first string is "Hello" and the second string is "World", then after concatenation the destination string becomes "HelloWorld".
In C, a string is an array of characters ending with the null character '\0'. To concatenate two strings manually, the program first finds the null character at the end of the destination string. Then it copies characters from the source string into the destination string, starting from that position.
The function uses two pointers: dest points to the destination string, and src points to the source string. First, dest is moved to the end of the destination string. Then, in a loop, each character from src is copied to dest, and both pointers are incremented. Finally, a null character is added to mark the end of the combined string.
💡 In one line: Move the destination pointer to its null character, copy each source character there, advance both pointers, and finish by adding '\0'.
The Three Steps of Concatenation
| Step | Pointer operation | Effect |
|---|---|---|
| 1. Reach the end of the destination | while (*dest != '\0') dest++; | dest now points to the null character of the first string |
| 2. Copy the source string | while (*src != '\0') { *dest = *src; dest++; src++; } | Each character of the source string is copied after the destination string |
| 3. Terminate the result | *dest = '\0'; | The combined string is properly ended |
The destination array must have enough space to store both strings plus the final null character. For example, to concatenate a 5-character string and a 5-character string, the destination array must be able to hold at least 11 characters: 5 + 5 + 1.
This program does not use the library function strcat(). Instead, it implements the same logic manually using pointers, which helps you understand how C strings are stored and processed in memory.
Complete C Program
Program: concatenate two strings using pointers
#include <stdio.h>
#define MAX 200
/* Concatenate source string at the end of destination string. */
void concatenate_strings(char *dest, const char *src) {
/* Move dest to the null character of the destination string */
while (*dest != '\0') {
dest++;
}
/* Copy characters from source to destination */
while (*src != '\0') {
*dest = *src;
dest++;
src++;
}
/* Add the terminating null character */
*dest = '\0';
}
int main(void) {
char str1[MAX];
char str2[MAX];
printf("Enter the first string: ");
if (fgets(str1, sizeof(str1), stdin) == NULL) {
printf("Invalid input.\n");
return 1;
}
printf("Enter the second string: ");
if (fgets(str2, sizeof(str2), stdin) == NULL) {
printf("Invalid input.\n");
return 1;
}
/* Remove trailing newline characters entered by fgets */
char *p = str1;
while (*p != '\0') {
if (*p == '\n') {
*p = '\0';
break;
}
p++;
}
p = str2;
while (*p != '\0') {
if (*p == '\n') {
*p = '\0';
break;
}
p++;
}
concatenate_strings(str1, str2);
printf("\nConcatenated string: %s\n", str1);
return 0;
}
Program Output
Enter the first string: Hello
Enter the second string: World
Concatenated string: HelloWorld
A second run, with strings containing spaces:
Enter the first string: Sankalan
Enter the second string: Data Tech
Concatenated string: SankalanData Tech
In the first run, the function finds the null character after "Hello" and copies "World" from that position. In the second run, spaces inside the strings are preserved because fgets() reads the complete line, including spaces.
Step-by-Step Explanation
Let us understand how the function joins the two strings using pointers.
1. The function signature
void concatenate_strings(char *dest, const char *src) receives two character pointers. The dest pointer points to the destination string, which will contain the final combined result. The src pointer points to the source string, whose characters will be added at the end.
2. Moving to the end of the destination
The first loop, while (*dest != '\0') dest++;, moves dest forward until it reaches the null character. For example, if the destination string is "Hello", the pointer stops at the memory location just after the character 'o'.
3. Copying the source characters
The second loop copies one character at a time. The statement *dest = *src; copies the character pointed to by src into the location pointed to by dest. Then dest++ and src++ move both pointers to their next characters.
4. Adding the null character
When *src becomes '\0', the loop stops. At this point, dest points to the position where the combined string must end. The statement *dest = '\0'; adds the terminating null character.
5. Example trace
Suppose str1 = "Hello" and str2 = "World":
- Initially,
destpoints to'H'andsrcpoints to'W'. - The first loop moves
destto the null character after"Hello". - The second loop copies
'W','o','r','l', and'd'one by one. - After copying,
str1becomes"HelloWorld". - Finally,
'\0'is added at the end.
6. Why the destination must be large enough
The destination array must have space for both strings and the final null character. If it is too small, the function will write beyond the array boundary. This is called a buffer overflow and can cause unpredictable behavior or a program crash.
7. Why const char *src is used
The source string is declared as const char *src because the function only reads from it. The const keyword prevents accidental modification of the source string inside the function.
8. Why fgets is used instead of scanf
fgets() can read strings containing spaces, while scanf("%s") stops at the first whitespace character. Because fgets() also stores the newline character, the program removes it before concatenation.
9. Manual concatenation vs strcat
The standard library function strcat(dest, src) performs the same operation. Our user-defined function performs the same steps manually: find the end of dest, copy src, and add '\0'. Writing it manually is useful for learning pointer traversal and string memory layout.
10. Complexity summary
If the destination string has m characters and the source string has n characters, the time complexity is O(m + n). The function must traverse the destination string to find its end and then traverse the source string to copy it. Space complexity is O(1) because the function uses only pointer variables and does not allocate extra memory.
🎯 Remember this: To concatenate strings using pointers, first move dest to its null character, then copy every character from src, and finally write '\0' at the end. Always ensure the destination array is large enough.
Frequently Asked Questions
1. What does concatenation mean in C?
Concatenation means joining two strings into one string. For example, concatenating "Hello" and "World" produces "HelloWorld". The second string is added immediately after the first string.
2. Why do we move the destination pointer to '\0'?
The null character marks the end of the destination string. The source string must be copied starting from that position; otherwise, it would overwrite characters of the destination string.
3. What happens if the destination array is too small?
If the destination array does not have enough space, the function may write beyond its boundary. This is a buffer overflow, which can corrupt memory, cause a crash, or create a security vulnerability.
4. Can this function concatenate a string with itself?
It can, but only if the destination array has enough extra space. For example, concatenating "abc" with itself requires space for "abcabc" plus the null character. Also, the source and destination must not overlap in an unsafe way.
5. How is this different from strcat()?
strcat() is a standard library function that concatenates strings automatically. This program performs the same task manually using pointer traversal. The manual version is useful for understanding how C strings and pointers work internally.
6. What is the time complexity of this program?
The time complexity is O(m + n), where m is the length of the destination string and n is the length of the source string. The function traverses the destination once to find its end and traverses the source once to copy it. Space complexity is O(1).
💡 Tip: After implementing this program, try writing a version that returns the destination pointer, just like strcat(). Then use that returned pointer directly in a printf() statement.