Let us consider the below program.
Output of the program is str1 is geeks, str2 is forgeeks. So the above swap() function doesn’t swap strings. The function just changes local pointer variables and the changes are not reflected outside the function.
Let us see the correct ways for swapping strings:
Method 1(Swap Pointers)
If you are using character pointer for strings (not arrays) then change str1 and str2 to point each other’s data. i.e., swap pointers. In a function, if we want to change a pointer (and obviously we want changes to be reflected outside the function) then we need to pass a pointer to the pointer.
This method cannot be applied if strings are stored using character arrays.
Method 2(Swap Data)
If you are using character arrays to store strings then preferred way is to swap the data of both arrays.
This method cannot be applied for strings stored in read-only block of memory.
Please write comments if you find anything incorrect in the above article, or you want to share more information about the topic discussed above.
- Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ...
- Pointers in C and C++ | Set 1 (Introduction, Arithmetic and Array)
- Different methods to reverse a string in C/C++
- What's difference between char s and char *s in C?
- Structures in C
- How to pass a 2D array as a parameter in C?
- How to dynamically allocate a 2D array in C?
- Difference between pointer and array in C?
- Complicated declarations in C
- How to Count Variable Numbers of Arguments in C?
- Write one line functions for strcat() and strcmp()
- Do not use sizeof for array parameters
- gets() is risky to use!
- How does "void *" differ in C and C++?
- Storage for Strings in C