0

So I have a code sample in Dev C++ in which I am trying to swap the values of s1 and s2 and print it out but somehow, the values doesn't change. I checked the function and it displays the proper values correctly, but when in the main, the values does not change.

 void swap_pointers(char *x,char *y){
     char *tmp;
     tmp = x;
     x = y; 
     y = tmp; 
     printf("%s\n",x);
     printf("%s\n\n",y);
}

int main()
{
     char *s1, *s2;
     s1 = "I should print second";
     s2 = "I should print first";

     swap_pointers(s1,s2);
     printf("-AFTER SWAPPING-\n\n");
     printf("s1 is %s\n",s1);
     printf("s2 is %s\n",s2);

     return 0;
 }
Abraham
  • 11
  • 4
  • In C arguments are passed *by value*, meaning they are copied. Inside a function, all you have is the copies. Modifying a copy will not modify the original. To solve it I recommend that you do some research about *emulating pass by reference in C*. – Some programmer dude Nov 21 '18 at 08:47
  • Oh, is the code you're writing really C++? Or is it C? The only C++ specific bit is the lack of `void` as argument to the `main` function. If this is really C++, then the natural solution is to use [`std::swap`](https://en.cppreference.com/w/cpp/algorithm/swap) instead of making your own. Or if you do it for educational reasons then read about *references* (which C doesn't have). – Some programmer dude Nov 21 '18 at 09:01
  • You have websites where I can start atleast so I can solve this further? I just want my program to work so I can try to learn from those mistakes. – Abraham Nov 21 '18 at 09:23
  • First of all, asking for links is not [on topic](https://stackoverflow.com/help/on-topic). Secondly, we could not have provided proper links anyway since we don't know if you're programming in C or C++ (the `dev-c++` tag is for the development environment, not the language). Lastly, use your favorite search engine, it should be very good at finding websites. – Some programmer dude Nov 21 '18 at 09:26
  • I don't know if Dev C++ has a syntax of its own but I can say I'm programming in C++ platform. – Abraham Nov 21 '18 at 09:28
  • If you're really programming C++, then you seem to be using the wrong books or tutorials to teach you, since as I mentioned the code is over 99% plain C. I recommend you get a couple of books from [this list of excellent books](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list/388282#388282). and start over. Those books should also teach you how to solve the problem you ask about. – Some programmer dude Nov 21 '18 at 09:32

0 Answers0