-3

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
underscore_d
  • 6,309
  • 3
  • 38
  • 64
  • 3
    Maybe read the second part of [the article](https://www.geeksforgeeks.org/swap-strings-in-c/)? – Marco Bonelli Oct 02 '20 at 12:35
  • 2
    You're passing the string pointers by value into the swap function, so the swap there doesn't affect your str1 and str2 variables back in main(). – Rup Oct 02 '20 at 12:35

1 Answers1

4

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); 
Hatted Rooster
  • 35,759
  • 6
  • 62
  • 122
  • thanks but str1 and str2 are addresses when passed into swap function ,than why is it call by value , I am new to the programming please help and explain me? – Bhanu Arora Oct 03 '20 at 09:36