Sudhanshu Gupta Sudhanshu Gupta - 11 months ago 88
C Question

String swap by swap function

I have written code to swap strings, but I am not able to swap. What is the problem and how can I solve it by using a function,


#include <stdio.h>

void swap( char*,char*);
int main()
char *ptr[2] = {"hello", "morning"};
swap(ptr[0], ptr[1]);
printf("%s %s", ptr[0], ptr[1]);
return 0;

void swap(char *t1, char*t2)
char *t;
t = t1;

t1 = t2;
t2 = t;

I also tried to pass
(&ptr[0], &ptr[1])
, but here it shows a
segmentation fault
. Also I made a char,
*p1 = ptr[0], char *p1 = ptr[1]
, and then passes
, and
, but still I get a segmentation fault.

Answer Source

C function arguments are pass-by-value. You're passing the value of addresses to your swap function, and expecting those values, the addresses, to change. But only the copies of the addresses in your swap function change.

To change the actual passed-in addressed, you'll need an aditional level of reference:

void swap(char **t1, char **t2)
    char *t;

    t = *t1;
    *t1= *t2;
    *t2 = t;

And call this swap like so: swap(&ptr[0], &ptr[1]);