Ravi Ravi - 6 months ago 25
C Question

swapping string in c using pointer

Need help

this is my code

void swapstringfun()
int i=0,j=0;
char *str=(char *)malloc(sizeof(char)*15);
char *mystr=(char *)malloc(sizeof(char)*15);
printf("Please enter first string :\t");
printf("Please enter second string :\t");
while(*(str+i)!='\0' && *(mystr+i)!='\0')
*(str+i) ^=*(mystr+i);
*(mystr+i) ^=*(str+i);
*(str+i) ^=*(mystr+i);
printf("%s swapped to %s",str,mystr);

I wrote the above code to swap the string using XOR operator. The problem with this code is. when my input is lets say.. RAJESH and ASHISH. Then, it shows output ASHISH and RAJESH. And, that is expected.

But, when input is let say.. ABHISHEK and CODER .Then, output is CODERHEK and ABHIS. But, the expected output is CODER and ABHISHEK. Anyone help me to solve this problem. I will appreciate.


You iterate and swap until you reach the end of the shorter string

while(*(str+i)!='\0' && *(mystr+i)!='\0')

(or both, if the lengths are equal). To iterate until you reach the end of the longer string, you need an || instead of the && and be sure that 1. both pointers point to large enough memory blocks, and 2. the shorter string ends with enough 0 bytes. So you should calloc the memory, not malloc.

However, you should swap the pointers, really,

char *tmp = str;
str = mystr;
mystr = tmp;