Hi,
Like almost all of beginners I have problem understanding pointers.
Please, look at this piece of code, and please explain me why myswap
function doesn't work as it's supposed to do, whereas myswap2 is doing
exactly what I want it to do - swaping pointers. Where I made a mistake?
Thanks
void myswap(char *pa, char *pb){
char *tmp;
tmp=pa;
pa=pb;
pb=tmp;
}
void myswap2(char *sw[]){
char *tmp;
tmp=sw[0];
sw[0]=sw[1];
sw[1]=tmp;
}
int main(void){
char *a="1111", *b="2222", *A[]={"1111","2222" };
printf("1: %s, 2: %s\n", a,b); //stdout: 1: 1111, 2: 2222
myswap(a,b);
printf("1: %s, 2: %s\n", a,b); //stdout: 1: 1111, 2: 2222
//Not working :/
printf("2: %s, 2: %s\n", A[0],A[1]); //stdout: 1: 1111, 2: 2222
myswap2(A);
printf("2: %s, 2: %s\n", A[0],A[1]); //stdout: 1: 2222, 2: 1111
//Here it works!
return 0;
}
--
Piotrek
Like almost all of beginners I have problem understanding pointers.
Please, look at this piece of code, and please explain me why myswap
function doesn't work as it's supposed to do, whereas myswap2 is doing
exactly what I want it to do - swaping pointers. Where I made a mistake?
Thanks
void myswap(char *pa, char *pb){
char *tmp;
tmp=pa;
pa=pb;
pb=tmp;
}
void myswap2(char *sw[]){
char *tmp;
tmp=sw[0];
sw[0]=sw[1];
sw[1]=tmp;
}
int main(void){
char *a="1111", *b="2222", *A[]={"1111","2222" };
printf("1: %s, 2: %s\n", a,b); //stdout: 1: 1111, 2: 2222
myswap(a,b);
printf("1: %s, 2: %s\n", a,b); //stdout: 1: 1111, 2: 2222
//Not working :/
printf("2: %s, 2: %s\n", A[0],A[1]); //stdout: 1: 1111, 2: 2222
myswap2(A);
printf("2: %s, 2: %s\n", A[0],A[1]); //stdout: 1: 2222, 2: 1111
//Here it works!
return 0;
}
--
Piotrek
Comment