2 2 votes why this function not do swapping #include <stdio.h> void swap(char *str1, char *str2) { char *temp = str1; str1 = str2; str2 = temp; } int main() { char *str1 = "Gate"; char *str2 = "Overflow"; swap(str1, str2); printf("str1 is %s, str2 is %s", str1, str2); return 0; } Output : str1 is Gate, str2 is Overflow Programming in C programming-in-c pointers + – tiger 1.2k views answer comment Share Follow Print 0 reply Please log in or register to add a comment.
Best answer 3 3 votes In this function whatever the exchange you are doing, is local only since str1, str2 and temp char pointers are local to swap() function.That is the reason your swap function is not working. Sandeep Singh answered Dec 14, 2015 • selected Dec 14, 2015 by tiger Sandeep Singh comment Share Follow See all 5 Comments 5 5 Comments reply Show 2 previous comments Arjun commented Apr 27, 2016 reply Follow flag No call by reference in C. It can be simulated as follows: #include<stdio.h> void swap(char **str1, char **str2) { char *temp = *str1; *str1 = *str2; *str2 = temp; } int main() { char *str1 = "Gate"; char *str2 = "Overflow"; swap(&str1, &str2); printf("str1 is %s, str2 is %s", str1, str2); return 0; } 0 0 replyShare Jhunjhunuwala commented Apr 27, 2016 reply Follow flag Sir.. even now the strings are not swapped.. https://ideone.com/qR0S23 0 0 replyShare Arjun commented Apr 28, 2016 reply Follow flag Sorry, the pointer usage was not correct. See now.. 0 0 replyShare Please log in or register to add a comment.