Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

string swapping works well with char ** but not with char *

In this program I have swapped the first 2 names

#include<stdio.h>
void swap(char **,char **);
main()
{
 char *name[4]={"amol", "robin", "shanu" };
 swap(&name[0],&name[2]);
 printf("%s %s",name[0],name[2]);
}
void swap(char **x,char **y)
 {
 char *temp;
 temp=*x;
 *x=*y;
 *y=temp;
 }

This programs runs perfectly but when I use the function swap(char *,char *) it does not swap the address why? why I have to use pointer to pointer?

like image 260
Ghost Iscuming Avatar asked Jan 15 '23 17:01

Ghost Iscuming


2 Answers

I assume you understand that to swap integers you would have function like swap(int *, int *)

Similarly, When you want to swap strings which is char *. You would need function like swap(char **, char **).

In such cases, you take their pointers and swap their content (otherwise values will not be swapped once function returns). For integer content, pointer is int * and in case of strings content is char * pointer to it is char **.

like image 164
Rohan Avatar answered Jan 29 '23 09:01

Rohan


Pointers (like all values) are passed by value.

If you use swap(char * a,char * b) and write a = tmp; this changes only the local variable a and not the original variable in the caller.

This simpler example also doesn't work as intended for the same reason:

void change(int x) {
    x = 0; // Only changes the local variable.
}

int main(void) { 
    int x = 0;
    change(x);       // This does not have any effect.
    printf("%d", x); // 0 is printed
    return 0; 
} 

http://ideone.com/u7Prp

like image 33
Mark Byers Avatar answered Jan 29 '23 10:01

Mark Byers