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

int main () {
     char *str1 = "Hello", *str2 = "there!"
     fun1(str1, str2);
     printf("%s %s", str1, str2);
     return 0;
}

Given the code above, from my understand we pass the pointers by value, so if for example the values are str1 = 1000, str2 = 2000, fun1 switches them around, so str1 = 2000, str2 = 1000. So when we are trying to print them, we should get "there! Hello", but the answers says that it prints "Hello there!" and I don't understand why.. by switching them around str1's value should be the memory adress of the first character of "there!" and str2 of the first character of "Hello".. I feel like I'm missing something important..

MathCurious
  • 135
  • 3
  • 2
    You function `fun1` is swapping its copies of the pointers. It is not swapping the pointed-to data, and it is not doing anything to the `str1` and `str2` pointers in the caller. – Steve Summit Aug 13 '21 at 16:02
  • "from my understand we pass the pointers by value" - you answer your own question in the first sentence. – Crowman Aug 13 '21 at 16:03
  • The variables in the function are not the same as the variables in `main` – Barmar Aug 13 '21 at 16:03
  • so whenever we pass by value we create a copy of the passed down arguements? that is, new copies which have their own location in memory and have no connection once so ever with the original variables? – MathCurious Aug 13 '21 at 16:05
  • That is a good definition of pass-by-value. – stark Aug 13 '21 at 16:45
  • @MathCurious: Yes, `s1` and `s2` are different objects from `str1` and `str2`; the value of `str1` is copied to `s1`, the value of `str2` is copied to `s2`. Any changes to `s1` and `s2` do not affect the values of `str1` or `str2`. So `s1` and `s2` need to be *pointers to* `str1` and `str2` with type `char **`; in the body of `swap` you read and write to `*s1` and `*s2`, and the arguments to `swap` need to be `&str1` and `&str2`. – John Bode Aug 13 '21 at 17:27

1 Answers1

2

The pointers are passed by value, so switching values of s1 and s2 will not affect str1 and str2.

If you want functions modify what caller specifies, you should pass pointers to what should be modified like this:

#include <stdio.h>

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

int main (void) {
     char *str1 = "Hello", *str2 = "there!"
     fun1(&str1, &str2);
     printf("%s %s", str1, str2);
     return 0;
}
MikeCAT
  • 73,922
  • 11
  • 45
  • 70