0

I am new to these pointers concept. I would like to know why doesn't the code below swaps both the string (or) atleast the first letter of the string.

Program:

#include<stdio.h>
void swap(char* s1,char* s2)
{
 char* temp=s1;
 s1=s2;
 s2=*temp;
}
int main()
{
 char* str1="Hello";
 char* str2="Guys";
 swap(str1,str2);
 printf("%s\n%s\n",str1,str2);
 return 0;
}

The output of the code remains the same string stored for that variable str1 and str2.

Output:

Hello
Guys

Here what I wanted to know is that as we are passing both the string to the function why doesn't the swap takes place. As address are swapped within the function why does the output doesn't gets swapped?...Why does the main function posses the same string in their respective variables(i:e str1 and str2)

Krithick S
  • 408
  • 3
  • 15
  • 3
    In C function parameters are passed by value. So `s1` and `s2` are local variables in the function. Changing them in the function does not affect the caller's variables. – kaylum Jul 04 '20 at 08:14
  • @kaylum But we are passing the address of the variables 'str1' and 'str2' to the `swap()` function because the 'char *' type holds the address of the string and it passes to the function 'swap()' ...As address are passed why doesn't the output gets swapped? – Krithick S Jul 04 '20 at 09:04
  • If you want to modify what `main()`'s `str1` and `str2` point at, you have to pass *their* addresses to your swap function. – Shawn Jul 04 '20 at 09:37
  • In `main()` function even if we pass it as `swap(&str1,&str2)` the output remains the same as the previous one. – Krithick S Jul 04 '20 at 11:13
  • Did you add extra stars to the swap code? – Martin James Jul 04 '20 at 14:15
  • Even by adding `void swap(char** s1, char** s2)` at the function definition and even by adding the address in the function call `swap(&str1,&str2)` the output doesn't get swapped. It remains as the same output present above. – Krithick S Jul 04 '20 at 14:52
  • Did you add `*` to the assignments? `char *temp=*s1; *s1=*s2; *s2=temp;` – kaylum Jul 04 '20 at 21:32
  • By adding `*` to the assignments within the `swap()` function I could get the output with some garbage value. **Output** : `*0@ 00@` – Krithick S Jul 05 '20 at 08:01
  • Now what I wanted to know is that what does the function `swap()` perform and why doesn't it swap even when the address is passed to the function. – Krithick S Jul 05 '20 at 08:06

0 Answers0