0
main()

char *s1="Second";
char *s2="First";
swap(s1,s2);
printf("%s\n",s1);
printf("%s\n",s2);

I have as an exercise, to swap those 2 strings above (so that the one that executes the program will see "First Second" instead of "Second First"), by changing the values of their pointers, using the function swap (that I have to make).

3 Answers 3

3

This would do what you need

void swap(char **s1, char **s2){
  char *temp=*s1;
  *s1=*s2;
 *s2=temp;
}

int main(){
  char *s1="second";
  char *s2="first";
  swap(&s1,&s2);
  printf("%s",s1);
  printf("%s",s2);
 return 0;

}
Sign up to request clarification or add additional context in comments.

2 Comments

This is the best answer that is actually in C. It doesn't use tricks, and it doesn't use c++-only functionality.
Wow! This code may be genious for C lovers, but you changed the user's code: swap(&s1,&s2); is not swap(s1,s2);. IMHO, this is more serious than ignoring the tag.
0
char *a="vinod";
char *b="kumar";

a=(char*)((int)a+(int)b);
b=(char*)((int)a-(int)b);
a=(char*)((int)a-(int)b);
printf("%s%s",a,b);

1 Comment

Uhh.. aren't there serious buffer overflow issues here? I think you're really thinking about the XOR trick, but from what I've learned recently, that's actually an undefined behavior for non-integer (including pointer) types. While this may work sometimes, I'd recommend staying away from this solution. It's "tricky", likely not correct, and the compiler will do a good job for you if you do things the common way. Do what Liviu says and use a temporary pointer.
-1
inline void swap(char*& s1, char*& s2)
{
    char* temp = s1;
    s1 = s2;
    s2 = temp;
}

6 Comments

Well, I'm kind of new here, but I don't think it's alright to solve your school problems :p
This isn't valid C. This is C++. Either you mis-tagged your question, or this isn't a valid solution.
@xaxxon The tag is incorrect, you can't do swap(s1,s2); in C, see the next solution.
i'm guessing the question is tagged correctly but the asker doesn't know he can't do what he wants and needs to change the prototype for swap, not change languages.
@xaxxon Or maybe the teacher written the above code (the question) and demanded the implementation. I'm in a middle of a minor polemic right now: it seems it is common these days to learn directly C++ (and skip C entirely)
|

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.