• edited by
1,181 views
2 2 votes

why this function not do swapping

#include <stdio.h>

void swap(char *str1, char *str2) {
    char *temp = str1;
    str1 = str2;
    str2 = temp;
}

int main() {
    char *str1 = "Gate";
    char *str2 = "Overflow";
    swap(str1, str2);
    printf("str1 is %s, str2 is %s", str1, str2);
    return 0;
}

Output :

str1 is Gate, str2 is Overflow

1 Answer

Best answer
3 3 votes
In this function whatever the exchange you are doing, is local only since str1, str2 and temp char pointers are local to swap() function.That is the reason your swap function is not working.
• selected by
Position:
Show:

Related questions

1 1 vote
0 0 answers
2.6k
2.6k views
Ashish Roy 1 asked Mar 16, 2019
2,642 views
In the above 4 Statements which would print 123 as output ? Explain also.
2 2 votes
1 1 answer
2.6k
2.6k views
Nishi Agarwal asked Mar 10, 2019
2,575 views
int main() { int m=44; int *p=&m; int &r=m; int n=(*p)++; int *q=p-1; r= *(p)+1; ++*q; printf("m=%d n=%d r=%d",m,n,r); return 0; } Options:$m=44,\ n=46,\ r=45$$m=45,\ n=4...
1 1 vote
1 answers 1 answer
10.1k
10.1k views
bad_engineer asked Mar 13, 2016
10,090 views
void fun(int *p) { int q = 10; p = &q; } int main() { int r = 20; int *p = &r; fun(p); printf("%d", *p); return 0; }
1 1 vote
1 answers 1 answer
3.7k
3.7k views
Desert_Warrior asked May 15, 2016
3,736 views
main() { int arr2D[3][3]; printf("%d\n", ((arr2D==* arr2D)&&(* arr2D == arr2D[0])) ); }