why swap does not occur?Code:#include<stdio.h> #include<conio.h> void swap(char *t1,char *t2) { char *t; t=t1; t1=t2; t2=t; } int main() { char *p[2]={"Hello","Jaffna"}; swap(p[0],p[1]); printf("%s\n%s",p[0],p[1]); getch(); }
why swap does not occur?Code:#include<stdio.h> #include<conio.h> void swap(char *t1,char *t2) { char *t; t=t1; t1=t2; t2=t; } int main() { char *p[2]={"Hello","Jaffna"}; swap(p[0],p[1]); printf("%s\n%s",p[0],p[1]); getch(); }
The swap does happen. The trouble is, you're only swapping the pointers that are local to the swap function, whereas what you wanted to swap are what the pointers point to. Therefore, you should have char** parameters instead.
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)
laserlight is right you need to use char ** instead of char *, something like this :
Regards.Code:void swap(char **t1,char **t2) { char *t; t=*t1; *t1=*t2; *t2=t; } int main() { char *p[2]={"Hello","Jaffna"}; swap(&p[0],&p[1]); printf("%s\n%s\n",p[0],p[1]); getch(); return 0; }