0
0
CHow-ToBeginner · 3 min read

How to Swap Strings Using Pointer in C: Simple Guide

To swap strings using pointers in C, swap the pointers themselves instead of copying string contents. Use char * pointers and exchange their addresses to swap strings efficiently.
📐

Syntax

Swapping strings using pointers involves exchanging the addresses stored in two char * pointers. This avoids copying the actual string data.

  • char *str1, *str2; — pointers to strings
  • char *temp; — temporary pointer for swapping
  • Swap by temp = str1; str1 = str2; str2 = temp;
c
void swapStrings(char **a, char **b) {
    char *temp = *a;
    *a = *b;
    *b = temp;
}
💻

Example

This example shows how to swap two strings by swapping their pointers. It prints the strings before and after swapping.

c
#include <stdio.h>

void swapStrings(char **a, char **b) {
    char *temp = *a;
    *a = *b;
    *b = temp;
}

int main() {
    char *str1 = "Hello";
    char *str2 = "World";

    printf("Before swap:\nstr1 = %s\nstr2 = %s\n", str1, str2);

    swapStrings(&str1, &str2);

    printf("After swap:\nstr1 = %s\nstr2 = %s\n", str1, str2);

    return 0;
}
Output
Before swap: str1 = Hello str2 = World After swap: str1 = World str2 = Hello
⚠️

Common Pitfalls

Common mistakes when swapping strings using pointers include:

  • Trying to swap string contents character by character instead of swapping pointers, which is less efficient.
  • Swapping pointers incorrectly by not using pointers to pointers (char **), causing only local copies to swap.
  • Swapping string arrays directly instead of pointers, which is not allowed in C.
c
/* Wrong way: swapping local copies, no effect outside function */
void wrongSwap(char *a, char *b) {
    char *temp = a;
    a = b;
    b = temp;
}

/* Right way: swap pointers using pointers to pointers */
void correctSwap(char **a, char **b) {
    char *temp = *a;
    *a = *b;
    *b = temp;
}
📊

Quick Reference

Tips for swapping strings using pointers in C:

  • Use char ** to pass pointers to pointers for swapping.
  • Swap the pointers, not the string contents.
  • Do not try to swap arrays directly; arrays cannot be assigned.
  • This method is fast and memory efficient.

Key Takeaways

Swap strings in C by exchanging their pointers using char ** parameters.
Avoid copying string contents; swapping pointers is faster and simpler.
Always pass pointers to pointers to modify original pointer values.
Do not try to swap arrays directly as it is not allowed in C.
Use a temporary pointer variable to perform the swap safely.