Function Assignment 17 — Concatenate Two Strings Using a Function
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program: Concatenate Two Strings Using a Function

📑 On this page:
  • What "concatenate" means for C strings
  • Designing the stringConcat function
  • Complete C Program
  • Program Output
  • Step-by-Step Explanation
  • Frequently Asked Questions
📚 In this program, you will learn:
  • How to concatenate strings by walking to the end of one and copying from another
  • Why the destination buffer must be large enough — and how to check
  • How to write an in-place version (like strcat) and a version that returns a new buffer
  • Why the null terminator must be copied explicitly at the end
  • How buffer overflow happens and how to avoid it with snprintf

What "concatenate" means for C strings

Concatenating two strings means joining them end to end — taking the characters of the second string and appending them right after the last character of the first. So concatenating "hello" and " world" gives "hello world". In most languages, this is as simple as "hello" + " world". In C, it's a manual operation because strings are just byte arrays with a null terminator.

Here's the underlying process. Given two strings dest and src:

  1. Find the end of dest — the position of its null terminator.
  2. Overwrite that terminator with the first character of src.
  3. Copy the rest of src, character by character, right after.
  4. Finally, add a new null terminator to mark the end of the combined string.

The catch is step 2 and 3: you're writing into dest, so dest must have enough room. If dest is 10 bytes and src is 5 bytes, but dest already has 8 characters, you'd need 8 + 5 + 1 = 14 bytes — but you only have 10. Writing past the end of the buffer is the classic buffer overflow, and it's the source of more security vulnerabilities in C than any other single issue. The size check is not optional.

This assignment focuses on the mechanics of concatenation, including the size check. In practice, you'd use strcat (which doesn't check size) or strncat (which takes a limit) or snprintf (which formats and respects a maximum size). Writing your own version once teaches you exactly what all of those do — and why the safe versions exist.

A note on the two variants: the in-place version modifies dest (like strcat), while the new-buffer version allocates a fresh string and leaves both originals intact. The in-place version is more common (and matches the library), but the new-buffer version is safer for callers who don't want to think about buffer management.

💡 In one line: walk dest to its null terminator, then copy src character by character starting at that position, including the terminator. Before calling, verify that dest has at least strlen(dest) + strlen(src) + 1 bytes of space.

Two strings 'hello' and ' world' shown being joined into 'hello world', with a null terminator at the end.

Designing the stringConcat function

The signature matters here — the source should be const, the destination should not:

Part Choice Why
Function namestringConcatDescriptive. Alternately myStrcat or appendString.
Destinationchar *destNot const, because we'll write into it. This is where the result goes.
Sourceconst char *srcconst because we only read from it. This lets callers pass string literals without warnings.
Return typevoidThe result is in dest; nothing to return. Alternatively, return dest to match strcat's chaining convention.

The prototype:

void stringConcat(char *dest, const char *src);
                                

And the definition, using pointers:

void stringConcat(char *dest, const char *src) {
    while (*dest != '\0') {
        dest++;
    }
    while (*src != '\0') {
        *dest = *src;
        dest++;
        src++;
    }
    *dest = '\0';
}
                                

Three loops (well, two loops and a final write). The first finds the end of dest. The second copies from src to dest. The final line appends the null terminator to the combined string. It's a small function — maybe 10 lines — but each line is doing real work, and every line is worth understanding.

An equivalent version using array indices instead of pointers:

void stringConcat(char *dest, const char *src) {
    int i = 0, j = 0;
    while (dest[i] != '\0') i++;
    while (src[j] != '\0') {
        dest[i] = src[j];
        i++;
        j++;
    }
    dest[i] = '\0';
}
                                

Both versions do the same thing. The pointer version is idiomatic C, and it's shorter. The index version is more familiar to beginners and arguably easier to trace. Once you're comfortable with pointers, the pointer version is what you'll write. Either way, the logic is the same: find the end of the destination, then copy the source onto the end, then close with a terminator.

A returned-pointer version matches strcat's convention, where the function returns dest for chaining:

char *stringConcat(char *dest, const char *src) {
    char *d = dest;
    while (*d) d++;
    while ((*d++ = *src++)) { }
    return dest;
}
                                

This version packs the copy loop into a single line: *d++ = *src++ copies one character and advances both pointers; the while condition checks whether the copied character was '\0'. When it is, the loop exits — and the terminator has already been written into dest. This idiom is concise but tricky on a first read; the explicit version is clearer for learning. Both work.

⚠️ The buffer-overflow trap: the destination must have room for strlen(dest) + strlen(src) + 1 bytes. If it doesn't, you'll write past the end of the buffer — undefined behavior, usually a crash, sometimes silent corruption. Always check before concatenating. This is the single most important thing to internalize from this assignment.

Complete C Program

Program: concatenate two strings safely with a buffer check

#include <stdio.h>
#include <string.h>

/* Function prototype */
void stringConcat(char *dest, const char *src);

int main(void) {
    char dest[100];
    char src[100];

    printf("Enter the first string: ");
    if (!fgets(dest, sizeof(dest), stdin)) return 1;
    size_t dlen = strlen(dest);
    if (dlen > 0 && dest[dlen - 1] == '\n') dest[dlen - 1] = '\0';

    printf("Enter the second string: ");
    if (!fgets(src, sizeof(src), stdin)) return 1;
    size_t slen = strlen(src);
    if (slen > 0 && src[slen - 1] == '\n') src[slen - 1] = '\0';

    /* Safety check: is there room for both strings + '\0'? */
    size_t needed = strlen(dest) + strlen(src) + 1;
    if (needed > sizeof(dest)) {
        printf("Destination buffer too small (need %zu bytes, have %zu).\n",
               needed, sizeof(dest));
        return 1;
    }

    stringConcat(dest, src);

    printf("Concatenated: \"%s\"\n", dest);
    printf("Length: %zu\n", strlen(dest));

    return 0;
}

/* Concatenate src onto the end of dest */
void stringConcat(char *dest, const char *src) {
    while (*dest != '\0') {
        dest++;
    }
    while (*src != '\0') {
        *dest = *src;
        dest++;
        src++;
    }
    *dest = '\0';
}
                                    

The key safety check is if (needed > sizeof(dest)). This computes the total bytes required (both string lengths plus the terminator) and compares to the buffer's capacity. If the buffer is too small, it prints an error and exits without attempting the concatenation. That single check prevents the buffer overflow that would otherwise corrupt memory.

A version that returns a new buffer instead of modifying dest:

Variant: return a new concatenated string

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

char *concatCopy(const char *a, const char *b) {
    size_t la = strlen(a), lb = strlen(b);
    char *out = malloc(la + lb + 1);
    if (!out) return NULL;

    memcpy(out, a, la);
    memcpy(out + la, b, lb);
    out[la + lb] = '\0';
    return out;
}

int main(void) {
    char *result = concatCopy("hello", " world");
    if (!result) { printf("Out of memory.\n"); return 1; }
    printf("Result: %s\n", result);
    free(result);
    return 0;
}
                                    

This version allocates a new buffer of exactly the right size (la + lb + 1), copies both strings into it with memcpy, and terminates it. The original strings are untouched. The caller is responsible for freeing the result. This is safer for the caller (no risk of buffer overflow, since the buffer is sized exactly right), but requires attention to memory management.

And a version that never overflows, using snprintf:

Variant: safe concatenation with snprintf

#include <stdio.h>
#include <string.h>

int main(void) {
    char dest[20] = "hello";
    const char *src = " world!!";

    int written = snprintf(dest + strlen(dest),
                           sizeof(dest) - strlen(dest),
                           "%s", src);
    if (written < 0 || (size_t)written >= sizeof(dest) - strlen(dest)) {
        printf("Truncated output!\n");
    }
    printf("Result: %s\n", dest);
    return 0;
}
                                    

snprintf takes a buffer, its remaining size, a format string, and arguments. It writes at most size - 1 characters (leaving room for the terminator) and returns the number of characters that would have been written. If that return value is ≥ the size passed in, the output was truncated. This is the safest way to concatenate strings in standard C — no manual buffer math, no overflow risk. The tradeoff is a small performance overhead and slightly more code at the call site.

Program Output

A typical run:

Enter the first string: hello
Enter the second string: world
Concatenated: "helloworld"
Length: 10
                                

Notice there's no space between "hello" and "world" — concatenation doesn't add separators. If you want a space, include it in one of the strings:

Enter the first string: hello
Enter the second string:  world
Concatenated: "hello world"
Length: 11
                                

Note the space before "world" — the user typed it. Length is 11 because of the space. This is a good reminder: user input is taken literally, spaces and all.

With a phrase split across two lines:

Enter the first string: The quick brown
Enter the second string:  fox
Concatenated: "The quick brown fox"
Length: 19
                                

With an empty first string:

Enter the first string:
Enter the second string: abc
Concatenated: "abc"
Length: 3
                                

When the empty string is on the left, the result is just the right string. The concatenation logic correctly handles this because the first loop immediately finds the terminator at position 0, so the second loop copies from there.

With an empty second string:

Enter the first string: xyz
Enter the second string:
Concatenated: "xyz"
Length: 3
                                

The result is unchanged — the second loop doesn't execute because src is empty, and the final terminator is written at the end of the first string. Both empty-input edge cases work correctly.

And for the buffer-too-small case (if you try to concatenate something larger than 100 bytes):

Enter the first string: [a very long string...]
Enter the second string: [another very long string...]
Destination buffer too small (need 150 bytes, have 100).
                                

The check catches this before the overflow happens. The specific numbers depend on the input — the point is that the check reports them, and the program exits cleanly instead of crashing.

Step-by-Step Explanation

Let's walk through the in-place stringConcat function step by step.

1. The two strings in memory

Suppose dest = "hello" and src = "world". In memory:

dest:  h  e  l  l  o  \0  ?  ?  ?  ?     (buffer of size 100)
        0  1  2  3  4  5  6  7  8  9  ... 99
src:   w  o  r  l  d  \0
        0  1  2  3  4  5
                                

The ? marks show uninitialized bytes in dest — whatever happened to be there, we haven't touched them yet. The null terminator after "hello" is at index 5. That's where the concatenation will start.

2. Finding the end of dest

while (*dest != '\0') dest++; — advances the dest pointer until it points at the terminator. After the loop, dest points at index 5 (the '\0' slot).

Important: we've now lost the original starting position of dest. That's fine if we return void (the caller doesn't need the pointer back), but it means we can't inspect the beginning of the string from inside the function after this loop. If we wanted to return dest (as in the strcat-style version), we'd save the original pointer first.

3. Copying src to dest

while (*src != '\0') { *dest = *src; dest++; src++; } — the copy loop. On each iteration:

  1. Read the current character from src.
  2. Write it to dest.
  3. Advance both pointers.

Trace for src = "world", starting at dest = index 5:

  • Copy 'w' to dest[5], dest → index 6, src → index 1.
  • Copy 'o' to dest[6], dest → index 7, src → index 2.
  • Copy 'r' to dest[7], dest → index 8, src → index 3.
  • Copy 'l' to dest[8], dest → index 9, src → index 4.
  • Copy 'd' to dest[9], dest → index 10, src → index 5.
  • src[5] is '\0', loop ends.

Now dest points at index 10, which contains whatever was there (uninitialized memory). We need to terminate the string.

4. Writing the terminator

*dest = '\0'; — writes the null terminator at index 10. Now the memory looks like:

dest:  h  e  l  l  o  w  o  r  l  d  \0  ?  ? ...
        0  1  2  3  4  5  6  7  8  9  10 11 12 ...
                                

That's "helloworld" — 10 characters plus the terminator. Perfect. The original terminator at index 5 was overwritten by 'w', which is exactly what we wanted — we're not creating a new string, we're extending the existing one in place.

5. Why the buffer size matters

Here's the danger: the copy loop writes past the original null terminator. If dest's buffer isn't large enough to hold the combined string, the loop writes past the end of the buffer — into adjacent memory that might belong to other variables, other data structures, or (in a security-sensitive context) the stack frame of the function. This is the classic buffer overflow.

In our program, dest is a 100-byte buffer, and we check that strlen(dest) + strlen(src) + 1 ≤ 100 before calling. For "hello" + "world" = 10 + 1 = 11 bytes, which is well under 100 — safe. For very long strings, the check catches it and prints an error instead of overflowing.

6. The strlen calls in the check

strlen(dest) + strlen(src) + 1 — three pieces:

  • strlen(dest): characters currently in dest.
  • strlen(src): characters we'll be adding.
  • + 1: for the new terminator.

The sum is the total bytes required after concatenation. Comparing to sizeof(dest) gives us a definitive safety check. Note that strlen itself is O(n) — the check costs one pass over each string. That's a small overhead compared to the concatenation itself, and worth it for the safety.

7. Why const on src but not on dest

const char *src means "we promise not to modify the characters that src points to." The compiler will error if we try, and callers can pass const strings (like string literals) without warnings. char *dest means "we will modify what dest points to" — that's the whole point of concatenation. This asymmetry is standard for functions that modify one argument but only read another.

8. The empty-string edge cases

If dest is empty, the first loop doesn't run (the terminator is at index 0). The second loop copies all of src from index 0, then adds a terminator. Result: dest becomes a copy of src. If src is empty, the second loop doesn't run, and the final terminator is written at the original end of dest — the same position it was in, so dest is unchanged. Both cases work without any special handling.

9. The self-concatenation hazard

What if you call stringConcat(s, s)? The loop would copy from src (which is dest) while writing to dest. Because both pointers move forward at the same rate, the copy might or might not work correctly — it depends on whether the source pointer catches up with the writing position. In practice, self-concatenation is undefined behavior in C, and the standard strcat function explicitly documents it as undefined. Our implementation has the same caveat — don't call it with the same string on both sides.

10. Complexity

The function does strlen(dest) + strlen(src) character copies — total O(n + m) where n and m are the lengths of the two strings. The check in main costs another O(n + m) for the two strlen calls, so the overall work is linear in the total length. That's optimal — you can't concatenate two strings faster than reading both of them.

🔍 Try this: remove the size check in main and run the program with two 60-character strings. The combined length is 120, but dest is only 100 bytes. Depending on your compiler and platform, you'll see a crash, corrupted output, or (worst case) silent success with garbage at the end. This is the danger of unchecked buffer writes — restore the check afterwards, and remember why it's there.

Frequently Asked Questions

1. Why not just use strcat?

strcat is the standard library function that does exactly what we've implemented. In production code, use it — it's well-tested and optimized. But strcat doesn't do a size check (there's no size parameter), so it can overflow the destination if you're not careful. That's why strncat exists — it takes a maximum length. And why snprintf is often preferred — it knows the buffer size. Writing your own version teaches you what strcat does under the hood and why the size variants exist.

2. What happens if the destination isn't big enough?

Undefined behavior — usually a crash, sometimes silent corruption. The copy loop writes past the end of the buffer, overwriting adjacent memory. If that memory belongs to other variables, they get corrupted. If it's outside the stack frame, you get a segmentation fault. In security-sensitive code, this is exactly the bug that attackers exploit. Always check buffer sizes, or use snprintf/strncat.

3. Why do we need to write the null terminator at the end?

Because the copy loop stops when it encounters the null terminator in src — but it doesn't write that terminator into dest. If we didn't add it explicitly, dest would have all the copied characters but no terminator, so subsequent string operations (like strlen or printf("%s")) would read past the end of the concatenated string, into garbage bytes. Always write the terminator.

4. Can I concatenate more than two strings?

Yes, by chaining: stringConcat(a, b); stringConcat(a, c); — after the first call, a contains "a+b", and after the second it contains "a+b+c". Just make sure a's buffer is large enough for all of them at every step. Alternatively, write a variadic version (using <stdarg.h>) that takes a variable number of strings, but that's more complex than most needs require.

5. What if the strings contain non-ASCII (UTF-8) characters?

Concatenation works byte-by-byte, so as long as both strings are valid UTF-8 (or any other self-synchronizing encoding), the result is valid UTF-8. The null terminator is a single byte (0x00) and doesn't appear as part of any valid UTF-8 multi-byte sequence, so it's unambiguous. So our function works correctly for UTF-8, as long as the caller respects the encoding (e.g., doesn't truncate in the middle of a multi-byte sequence). This is one of the happy properties of null-terminated byte strings.

6. How is concatenation different from copying?

Copying (like strcpy) overwrites the destination from the start — it doesn't care what was already there. Concatenation appends to the destination — it finds the current end and writes from there. So copying "hello" into a buffer that had "world" gives "hello"; concatenating gives "worldhello". Both are useful, for different purposes. And both need careful buffer-size checking to avoid overflow.

💡 Tip: Once this works, try implementing stringCompare — the function that underlies strcmp. It walks both strings in parallel, comparing characters until it finds a difference or reaches the end of one. That's the third core string function (length, concatenation, comparison), and having all three written by hand gives you a complete picture of how C string handling works. After that, you'll never be confused about what <string.h> is doing — you'll have built the same primitives yourself.

📖 Related Tutorials

  • Introduction to Functions in C
  • What Are Pointers in C?
  • Function Definition
  • Function Declaration
  • Types of Functions
  • Previous: Find the Length of a String Using a Function
  • Next: Find the Maximum Element in an Array Using a Function
  • All 33 Function Assignments

Previous Topic: -->> 16. Find the Length of a String Using a Function   ||   Next Topic: -->> 18. Find the Maximum Element in an Array Using a Function


C Language

  • Home
  • Why C Language
  • History of C Language
  • Applications of C Language
  • Introduction To C
    • What is Program?
    • Structure of C Program
    • Working Of C Program
    • CHARACTER SET
    • VARIABLES AND IDENTIFIERS
    • BUILT-IN DATA TYPES
    • OPERATORS AND EXPRESSIONS
    • CONSTANTS AND LITERALS
    • SIMPLE ASSIGNMENT STATEMENT
    • BASIC INPUT/OUTPUT STATEMENT
    • SIMPLE 'C' PROGRAMS
    • Assignments
  • Operators in C Programming
    • Arithmetic Operators
    • Assignment Operators
    • Increment and Decrement Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Other Operators
    • Assignments
  • CONDITIONAL STATEMENTS
    • DECISION MAKING WITHIN A PROGRAM
    • CONDITIONS
    • IF STATEMENT
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • SWITCH CASE
    • Assignments
  • LOOPS STATEMENTS
    • Introduction to Loops
    • GO TO Statement
    • Do while Loop
    • While Loop
    • Nested While Loop
    • Difference Between While and Do while
    • Difference Between Goto and loop
    • while loop assignments
    • C FOR Loop
    • C For loop examples
    • Nested for loop
    • Nested for loop examples
    • Infinite while Loops
    • Infinite for Loops
    • Continue in Loops
    • break in Loops
    • difference while do..while & for
    • Assignments
  • Arrays
    • One Dimensional Array
    • Declaring 1D Arrays
    • Initilization of 1D arrays
    • Accessing element of one 1D Array
    • Read and Display 1D Arrays
    • Two Dimensional Arrays
    • Declare 2D Arrays
    • Read and Display 2D Arrays
    • Assignments/Examples
  • Functions
    • Introduction
    • Need For User-Defined Function
    • Multiple Function Program
    • Modular Programming
    • Elements Of User Defined Function
    • Function Definition
    • Function Declaration
    • Types of functions
    • Nesting of Function
    • Recursion
    • Passing Array To Functions
    • Scope,Visibility and Lifetime of Variables
    • Assignments
  • Structure
    • Introduction
    • Array vs Structure
    • Defining Structure
    • Declaring Structure Variables
    • Type Defined Structure
    • Accessing Structure Members
    • Structure Initilization
    • Copying & Comparing Structure Variables
    • Array of Structure
    • Arrays Within Structure
    • Structures Within Structures
    • Structures and Functions
    • Structure Examples/Assignments
  • Union
    • Define Union
    • Create and use Union
    • Difference Between Structure and Union
    • Union Examples
    • Union FAQ
  • Pointers
    • What Are Pointers In C?
    • How Do We Use Pointers In C?
    • Declaration Of A Pointer
    • The Initialization Of A Pointer
    • Syntax Of Pointer Initialization
    • Use Of Pointers In C
    • The Pointer To An Array
    • The Pointer To A Function
    • The Pointer To A Structure
    • Types Of Pointers
    • The Null Pointer
    • The Void Pointer
    • The Wild Pointer
    • The Near Pointer
    • The Huge Pointer
    • The far Pointer
    • dangling pointer
    • Accessing Pointers- Indirectly And Directly
    • Pros Of Using Pointers In C
    • Cons Of Pointers In C
    • Applications Of Pointers In C
    • The & Address Of Operator In C
    • How To Read The Complex Pointers In C?
    • Practice Problems On Pointers
  • File Processiong
    • File Handling In C
    • Types Of Files In C
    • Operations Done In File Handling
    • File Examples
    • Binary Files
    • count words,lines in a file
    • Copy files
    • Update File
    • count vowels in a file
  • Preprocessor
    • Macro substitution division
    • File Inclusion
    • Conditional Compilation
    • Other directives
    • Examples
  • Dynamic Memory Allocation
    • malloc
    • calloc
    • free
    • realloc
    • Examples
  • Storage Classes
  • Graphics
  • Frequently Asked Interview Questions (FAQ)
    • Introduction To C FAQ
    • Operators FAQ
    • Conditional Statements FAQ
    • Loops FAQ
    • Arrays FAQ
    • Function FAQ
    • Structure FAQ
    • Pointers FAQ
    • Files FAQ
    • Storage classes FAQ
    • Dynamic Memory FAQ
  • Programs/Assignments
    • Introduction To C
    • Operators
    • Conditional Statements
    • Loops
    • Arrays
    • Function
    • Structure
    • Pointers
    • Files
    • Storage classes
    • Dynamic Memory
  • Case Studies
  • Multiple Choice Questions
    • Introduction To C MCQ
    • Operators MCQ
    • Conditional Statements MCQ
    • Loops MCQ
    • Arrays MCQ
    • Function MCQ
    • Structure MCQ
    • Pointers MCQ
    • Files MCQ
    • Storage classes MCQ
    • Dynamic Memory MCQ
    • More MCQ

Get in touch

  • tech2dsm@gmail.com

© Sankalan Data Tech. All rights reserved.