Ravi
Ravi

Reputation: 31397

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);
   system("cls");
   printf("Please enter first string :\t");
   scanf("%s",str);
   printf("Please enter second string :\t");
   scanf("%s",mystr);
   while(*(str+i)!='\0' && *(mystr+i)!='\0')
   {
     *(str+i) ^=*(mystr+i);
     *(mystr+i) ^=*(str+i);
     *(str+i) ^=*(mystr+i);
     i++;
   }
   printf("%s swapped to %s",str,mystr);
   getch();
   main();
}

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.

Upvotes: 1

Views: 1876

Answers (3)

alk
alk

Reputation: 70903

You also need to swap the terminating 0, as its part of what is called a string in C.

The 0 is the stopper element in the character array, describing the string.

Upvotes: 1

Starkey
Starkey

Reputation: 9781

You need to XOR the entire length of both strings. Since in your second example, the strings are different lengths, your algorithm won't work.

This is the statement you'll have to reconsider:

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

Upvotes: 0

Daniel Fischer
Daniel Fischer

Reputation: 183858

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;

Upvotes: 2

Related Questions