+ 11

Reflect changes using call by reference

I am trying to swap two strings by swapping there base address but didn't work out, any idea whats the problem in this code? https://code.sololearn.com/c0U6JVArNHAh/?ref=app

7th Jul 2019, 6:20 AM
Aaditya Deshpande
Aaditya Deshpande - avatar
3 odpowiedzi
+ 6
It's because you don't actually change anything. Let's say that the value of s1 and s2 is 0x4800 and 0x4820 respectively, those value are the base address of the strings. After that, you pass those value to the swap function. Whatever it does in the function won't change s1 and s2 since you only pass its value not its address. It's basically like swaping integers with this function swap(int x, int y). Therefore, you should use this instead void func(char **s1,char **s2) { char *t; t=*s1; *s1=*s2; *s2=t; printf("\nin function %s %s",*s1,*s2); } And call the function like this func(&s1, &s2)
7th Jul 2019, 6:52 AM
Agent_I
Agent_I - avatar
0
hi
8th Jul 2019, 3:39 AM
Hikmatillo Dovudxonov