1

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.

2
  • Please indent your code properly. Commented Nov 4, 2012 at 16:37
  • 1
    Using xor is a rather silly way to swap two values. Using a temporary variable is both safer and faster. Commented Nov 4, 2012 at 16:45

3 Answers 3

2

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;
Sign up to request clarification or add additional context in comments.

2 Comments

@coders But, as indicated by the bolded text, that is dangerous.
ok got it. i will go through the concept of malloc and calloc. I mean, their differences and usage.
1

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.

Comments

0

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')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.