Pointer Assignment 30 — Swap Two Strings Using a Function and Pointers
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program: Swap Two Strings Using Pointers — Pointer Swap vs Content Swap

📑 On this page:
  • Two Ways to Swap Strings — Which One You Need
  • The Two Approaches Compared
  • Complete C Program
  • Program Output
  • Step-by-Step Explanation
  • Frequently Asked Questions
📚 In this program, you will learn:
  • Why swapping pointers is O(1) and swapping contents is O(n)
  • When you should swap char * values (pointer swap) vs. swap the bytes (content swap)
  • Why pointer swap requires char ** — and why that surprises beginners
  • Why content swap on strings of different lengths is tricky
  • Why you can't swap string literals at all

Two Ways to Swap Strings — Which One You Need

"Swap two strings" is ambiguous in C, and the right answer depends on what you actually have. If you have two char * pointer variables that point at two strings, "swapping the strings" usually means exchanging the pointers — a now points at what b pointed at, and vice versa. This is O(1) and doesn't touch the string bytes at all. If you have two char arrays (fixed buffers) that hold the string data, "swapping the strings" means exchanging the bytes in the buffers themselves. This is O(n) and requires walking both buffers.

The two approaches look similar — both are "swaps" — but they have completely different types, costs, and use cases. Pointer swap takes char ** parameters and does three assignments, regardless of string length. Content swap takes char * parameters and loops over the characters, which means it needs to worry about the strings' relative lengths and whether the destination buffers have room. Confusing the two is a common source of bugs.

There's a further constraint: you can't swap string literals at all. Literals like "Hello" live in read-only memory, and any attempt to write through them is undefined behaviour. If you have char *a = "Hello";, you can still swap the pointers (a and another char *), because you're only modifying the pointer variables. But you can't swap the contents, because the contents are read-only. The pointer swap works for literals; the content swap requires writable arrays.

💡 In one line: Swap pointers (char **) to redirect what the variables point at — O(1) and safe for literals. Swap contents (char *) to exchange bytes in writable buffers — O(n) and length-aware.

Diagram comparing pointer swap (two char* variables exchanging addresses) with content swap (two char buffers exchanging bytes through a temporary buffer)

The Two Approaches Compared

Aspect Pointer swap Content swap
Signaturevoid swap_ptrs(char **a, char **b)void swap_contents(char *a, char *b)
Bodychar *t = *a; *a = *b; *b = t;Swap bytes up to the null terminator, with a temporary buffer
TimeO(1)O(n)
Extra spaceO(1) — one char *O(n) if a temp buffer is used, O(1) if character-by-character
Works on literals?Yes — only the pointers changeNo — literals are read-only
Handles different lengths?Yes — triviallyTricky — buffer capacity must be sufficient for the longer string
When to useCaller has char * variables that should point at each other's stringsCaller has char arrays whose byte contents must be exchanged

For most practical purposes — sorting an array of strings, reordering tokens, and so on — the pointer swap is what you want. Sorting a list of strings by swapping their pointers is dramatically faster than swapping their contents, because each swap is O(1) instead of O(len). This is why qsort on an array of char * is fast: it swaps pointers, not bytes. The content swap is used when the strings are stored in fixed-size buffers that can't be re-pointed, or when the API contract requires the bytes to move.

The content swap has a subtlety: if the two strings have different lengths, the longer string's tail doesn't have a counterpart in the shorter one. The usual convention is that the shorter string's terminator goes into the longer buffer at the position where the shorter string ended, and the longer string's tail then has nowhere to go — which means the content swap is only truly a swap if both buffers have enough room for the longer string. A robust content swap either requires equal buffer capacities and equal string lengths, or it treats the buffers as fixed-size and simply swaps min(len(a), len(b)) characters, leaving the tails alone — but then it's not really a swap, it's an exchange of prefixes.

Complete C Program

Program: two ways to swap two strings using pointers

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

/* ---------- Approach A: swap the pointers (O(1)) ---------- */
/* After the call, *a points where *b used to point and vice versa. */
void swap_ptrs(const char **a, const char **b) {
    const char *tmp = *a;
    *a = *b;
    *b = tmp;
}

/* ---------- Approach B: swap contents in place (O(n)) ---------- */
/* Requires writable buffers of equal capacity. Swaps characters up
   to the shorter terminator, then swaps the tails up to capacity. */
void swap_contents(char *a, char *b, size_t capacity) {
    for (size_t i = 0; i < capacity; i++) {
        char tmp = a[i];
        a[i] = b[i];
        b[i] = tmp;
    }
}

int main(void) {
    /* --- Approach A: pointers --- */
    const char *s1 = "Hello";
    const char *s2 = "World";

    printf("Before pointer swap:\n");
    printf("  s1 = \"%s\"  (address %p)\n", s1, (const void *)s1);
    printf("  s2 = \"%s\"  (address %p)\n", s2, (const void *)s2);

    swap_ptrs(&s1, &s2);

    printf("After pointer swap:\n");
    printf("  s1 = \"%s\"  (address %p)\n", s1, (const void *)s1);
    printf("  s2 = \"%s\"  (address %p)\n", s2, (const void *)s2);

    /* --- Approach B: contents of writable arrays --- */
    char buf1[16] = "Hello";
    char buf2[16] = "World";

    printf("\nBefore content swap:\n");
    printf("  buf1 = \"%s\"\n", buf1);
    printf("  buf2 = \"%s\"\n", buf2);

    swap_contents(buf1, buf2, sizeof(buf1));

    printf("After content swap:\n");
    printf("  buf1 = \"%s\"\n", buf1);
    printf("  buf2 = \"%s\"\n", buf2);

    return 0;
}
                                    

Program Output

Before pointer swap:
  s1 = "Hello"  (address 0x...)
  s2 = "World"  (address 0x...)
After pointer swap:
  s1 = "World"  (address 0x...)    ← now points at s2's old address
  s2 = "Hello"  (address 0x...)    ← now points at s1's old address

Before content swap:
  buf1 = "Hello"
  buf2 = "World"
After content swap:
  buf1 = "World"
  buf2 = "Hello"
                                

The pointer swap shows the addresses exchanging: after the call, s1 points at what s2 used to point at, and vice versa. Notice that the actual characters "Hello" and "World" never moved — only the pointers did. The content swap, by contrast, exchanges the bytes in the buffers: buf1 and buf2 each contain the other's former string, and the bytes really did move (through the temporary char tmp inside swap_contents). Both approaches produce a "swapped" result, but they do it in fundamentally different ways.

Step-by-Step Explanation

Let's walk through both approaches and see why the types and mechanics differ.

1. Why pointer swap takes char **

The function's job is to modify the caller's char * variables. In C, to modify a variable through a function, you must pass a pointer to it. A char * variable is modified through a char ** — a pointer to a pointer. So if the caller has const char *s1 and const char *s2, the function receives const char **a and const char **b, and the call is swap_ptrs(&s1, &s2). This "pointer to pointer" indirection is what trips up beginners, but it's the same pattern as scanf("%d", &x) — the function needs the address of the variable to write to it.

2. The pointer swap body

const char *tmp = *a; saves the pointer that *a (which is s1) currently holds. *a = *b; overwrites s1 with the pointer that s2 holds. *b = tmp; writes the saved pointer into s2. Three assignments, done. The string bytes are never touched — only the two pointer variables change. The const on char reflects the caller's intent: the strings themselves are read-only, but the pointers can be reassigned.

3. Why pointer swap works on literals

String literals are read-only, so any attempt to write through a char * pointing at a literal is undefined behaviour. But pointer swap doesn't write through the pointers — it writes to the pointer variables themselves, which are ordinary local variables. s1 = "World"; doesn't modify the string "World"; it changes what s1 points at. So swapping s1 and s2 is perfectly safe even when both point at literals. This is a key advantage of the pointer swap: it works with any strings, read-only or writable, because it never touches the bytes.

4. The content swap body

swap_contents(char *a, char *b, size_t capacity) iterates over the buffers and swaps each byte through a temporary char. The capacity parameter is the number of bytes to swap — typically sizeof(buf1) or the length of the shorter buffer. For fixed-size character arrays, this swaps everything, including the null terminator and any unused trailing bytes. The result is that the two buffers' contents are completely exchanged. If the buffers are exactly the same size, this is a clean swap. If one buffer is longer than the other, the shorter string ends up with trailing garbage from the longer buffer's tail — a subtle bug to avoid.

5. Why capacity matters

Suppose you have char a[10] = "Hi"; and char b[10] = "Hello";. If you swap contents up to strlen("Hi") = 2 characters, you exchange 'H' and 'h' and 'i' and 'e', but then you also need to write the terminator somewhere. The correct behaviour depends on what "swap" means for different-length strings. The simplest robust version is: swap exactly capacity bytes, where capacity is at least the length of the longer string plus one. If both buffers are equal-sized arrays (as in char buf1[16], buf2[16]), then sizeof gives you a valid capacity, and everything — terminator included — swaps cleanly. For variable-length strings, content swap is much trickier and often not what you want — use pointer swap instead.

6. Tracing the pointer swap of "Hello" and "World"

Before the call: s1 holds address A (where "Hello" lives), s2 holds address B (where "World" lives). Inside swap_ptrs(&s1, &s2), a points at s1 and b at s2. Then:

  • tmp = *a; — tmp holds A (the address of "Hello").
  • *a = *b; — s1 now holds B (the address of "World").
  • *b = tmp; — s2 now holds A (the address of "Hello").

After the call, s1 points at "World" and s2 points at "Hello". The strings themselves haven't moved — only the pointers. printf("%s", s1) now prints "World" because s1 points at the "World" characters.

7. Tracing the content swap of "Hello" and "World"

Before the call: buf1 contains {'H','e','l','l','o','\0',...}, buf2 contains {'W','o','r','l','d','\0',...}. The loop runs for i = 0..15:

  • i=0: tmp='H', buf1[0]='W', buf2[0]='H'. Now buf1="Wello...", buf2="Horld...".
  • i=1: tmp='e', buf1[1]='o', buf2[1]='e'. buf1="Wollo...", buf2="Herld...".
  • ... and so on. After 5 iterations, buf1="World" and buf2="Hello".
  • The loop continues to i=15, swapping the terminators and the trailing zeros, so both buffers remain valid C strings of exactly 16 bytes of content.

The key difference from the pointer swap: the bytes in the buffers really did move. buf1's memory at index 0 now holds 'W' instead of 'H', and vice versa. This is why the content swap requires writable buffers — you can't do this with string literals, which is why the function signature takes char * (not const char *).

8. Why the pointer swap is faster

The pointer swap does exactly three assignments, regardless of string length. The content swap does capacity iterations, which for long strings is a lot of work. If you're sorting thousands of strings, using content swap would make each comparison-comparison pair require a full copy of the string's bytes — the sort would be dominated by byte-copying. Using pointer swap, the sort only moves 8-byte pointers around, which is far faster. This is why "sort an array of strings" is almost always implemented with char * pointers, not char buffers.

9. Why the content swap needs equal buffer capacity

If buf1 has capacity 16 and buf2 has capacity 8, you can't swap all 16 bytes without writing past the end of buf2. The function's capacity parameter must be the smaller of the two buffers' capacities — or, if you want a full swap, both buffers must have capacity ≥ the length of the longer string plus one. In the program, both buffers are declared char[16], so sizeof is 16 for both and the full swap is safe. Passing sizeof(buf1) is correct because the capacities are equal; if they weren't, you'd need to pass min(sizeof(buf1), sizeof(buf2)).

10. Why you can't swap the contents of string literals

A literal like "Hello" has type char[N] for some N, but it lives in read-only memory. If you try swap_contents((char *)"Hello", ...), the function will attempt to write to the literal's bytes, which is undefined behaviour — usually a segmentation fault. The compiler might even warn you if you pass a literal directly, but char *p = "Hello"; loses that warning because the const-correctness is dropped. This is why the pointer swap approach is safer for constants: it never touches the bytes, so it works on literals without any casts. The lesson: for read-only or unknown-capacity strings, swap pointers; for writable buffers, you can swap contents.

11. Is there a way to swap contents without a temporary?

Yes, with the XOR trick or arithmetic swapping, but it's rarely worth it. The XOR swap: a[i] ^= b[i]; b[i] ^= a[i]; a[i] ^= b[i];. It avoids the temporary but does three XORs instead of three assignments, which is not faster on modern CPUs and is less readable. It also fails if a and b point to the same address (which would zero the value). The temporary-variable swap is the standard approach in C, and the compiler optimises it well. For a teaching example, the temporary version is clearer; for performance, all three are similar on modern hardware.

12. Complexity of both approaches

Pointer swap: O(1) time (three assignments), O(1) space (one temporary pointer). Content swap: O(min(len1, len2)) time if you stop at the terminator, or O(capacity) time if you swap the whole buffer — either way, O(n) in the length. Both are "optimal" for their respective operations, but they solve different problems. Pointer swap solves "make these two variables point at each other's data"; content swap solves "exchange these two buffers' bytes." Choose the one that matches your data structure and requirements.

🎯 Remember this: Pointer swap (char **) exchanges addresses — O(1), works on literals, no length concerns. Content swap (char *) exchanges bytes — O(n), needs writable buffers, must handle lengths carefully. For sorting, searching, or any algorithm that just reorders strings, use pointer swap; for truly moving data between fixed buffers, use content swap.

Frequently Asked Questions

1. Why does pointer swap use char ** instead of char *?

Because the function needs to modify the caller's char * variables — not the strings they point at. In C, to modify a variable from a function, you pass its address. The variable is a char *, so its address is a char **. The function dereferences *a and *b to read and write the caller's pointer variables. This is the same "pointer to a pointer" pattern used by scanf("%d", &x) to write through an int * — the double indirection is there because the thing being modified is itself a pointer.

2. Can I swap the contents of string literals?

No. String literals live in read-only memory, and any attempt to write to them is undefined behaviour — usually a segmentation fault. The compiler might warn you if the literal is passed directly, but if you assign it to a char * first, the warning goes away and the crash happens at runtime. Content swap requires writable buffers, which is why its parameter type is char * and not const char *. If you want to swap constants, use the pointer swap — it only modifies the pointer variables, never the literal bytes.

3. Why does content swap take a capacity parameter?

Because the function has no way to know how big the buffers are — pointers to char don't carry size information in C. If the caller passes char[16] buffers, the function needs to be told "16". Without a capacity parameter, the function would have to stop at the null terminator, which limits the swap to the length of the shorter string and leaves the longer string's tail untouched. For a true full swap of equal-capacity buffers, passing capacity = sizeof(buf1) (or min(sizeof(buf1), sizeof(buf2)) if they might differ) is the way to go. This is a recurring theme in C: functions that manipulate arrays need to be told how many elements there are.

4. What if the two strings have different lengths?

For pointer swap, nothing special — the function swaps the pointers, and each variable points at a new string of whatever length that string happens to be. For content swap, it depends on what you mean by "swap". If both buffers are equal capacity and you swap all capacity bytes, then each buffer ends up with the other's string, including the other's terminator and any trailing bytes. If the buffers are different capacities, a full swap is impossible in general — you'd have to either truncate the longer string (losing data) or use dynamic allocation (complex). For strings of different lengths in different-capacity buffers, pointer swap is almost always the right approach.

5. Is the XOR swap worth using instead of a temporary?

No, not for readability or performance. The XOR swap (a ^= b; b ^= a; a ^= b;) does three XOR operations instead of three assignments, and on modern CPUs it's not faster — in fact, it often creates a data dependency chain that pipelines worse. It also fails when a and b point to the same location (which zeroes the value). The temporary-variable swap is idiomatic, readable, and well-optimised by compilers. The XOR trick is an interesting historical curiosity but should not appear in production code.

6. What is the time and space complexity of each approach?

Pointer swap: O(1) time (three assignments) and O(1) space (one temporary pointer). Content swap: O(n) time (n character swaps) and O(1) extra space (one temporary char) — or O(n) space if you use a full temporary buffer instead of swapping in place. Both are optimal for their respective operations. Pointer swap is vastly faster for long strings, which is why it's the standard approach when the caller's data structure allows it (e.g., an array of char *).

💡 Tip: Once this works, try using the pointer swap to sort an array of strings. Declare const char *words[] = {"banana", "apple", "cherry"}; and sort them by swapping words[i] and words[j] — no character data is copied, only the pointers, so the sort is fast even for long strings. This is exactly what qsort does under the hood when called on an array of char *.

📖 Related Tutorials

  • 29. Factorial Using Pointers
  • 28. Check if a Number is Palindrome Using Pointers
  • 2. Swap Two Numbers Using Pointers
  • 21. Copy One String to Another Using a Function and Pointers
  • 19. Reverse a String Using Pointers
  • All 30 Pointer Assignments

Previous Topic: -->> 29. Factorial Using Pointers   ||   Next Topic: -->> All 30 Pointer Assignments


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.