Search code examples
cstringfunctionpointersswap

why is this string swap function in C not swap the strings?


I tried to swap strings using pointers but I do not know why is this not swapping the strings?

so can anyone explain me why is it happening and also correct it?

#include<stdio.h> 
void swap(char *str1, char *str2) 
{ 
  char *temp = str1; 
  str1 = str2; 
  str2 = temp; 
}   
   
int main() 
{ 
  char *str1 = "geeks"; 
  char *str2 = "forgeeks"; 
  swap(str1, str2); 
  printf("str1 is %s, str2 is %s", str1, str2); 
  getchar(); 
  return 0; 
} 

output:

str1 is geeks, str2 is forgeeks

Solution

  • You're passing the pointers by value so their copies are modified, not the original str1 and str2.

    You could modify the signature of swap to pass a pointer to a pointer, then modfying its value by dereferencing it:

    void swap(char** str1, char** str2) 
    { 
      char* temp = *str1; 
      *str1 = *str2; 
      *str2 = temp; 
    } 
    

    And

    char* str1 = "geeks"; 
    char* str2 = "forgeeks"; 
    swap(&str1, &str2);