In this program I have swapped the first 2 names
#include<stdio.h>
void swap(char **,char **);
main()
{
 char *name[4]={"amol", "robin", "shanu" };
 swap(&name[0],&name[2]);
 printf("%s %s",name[0],name[2]);
}
void swap(char **x,char **y)
 {
 char *temp;
 temp=*x;
 *x=*y;
 *y=temp;
 }
This programs runs perfectly but when I use the function swap(char *,char *) it does not swap the address why? why I have to use pointer to pointer?
I assume you understand that to swap integers you would have function like swap(int *, int *)
Similarly, When you want to swap strings which is char *. You would need function like swap(char **, char **).
In such cases, you take their pointers and swap their content (otherwise values will not be swapped once function returns). For integer content, pointer is int * and in case of strings content is char * pointer to it is char **.
Pointers (like all values) are passed by value.
If you use swap(char * a,char * b) and write a = tmp; this changes only the local variable a and not the original variable in the caller.
This simpler example also doesn't work as intended for the same reason:
void change(int x) {
    x = 0; // Only changes the local variable.
}
int main(void) { 
    int x = 0;
    change(x);       // This does not have any effect.
    printf("%d", x); // 0 is printed
    return 0; 
} 
http://ideone.com/u7Prp
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With