Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
322 views
in Technique[技术] by (71.8m points)

pointers - Why doesn't this swapping function work? (swapping strings in C)

I am trying to swap 2 entries in an array of strings, but my swap function doesn't swap when called.

swap(char*, char*);

int main() {
    char *ptsr[2] = { "x", "y" };
    swap(ptsr[0], ptsr[1]);
}

swap(char *t1, char *t2) {
    char *t;
    t = t1;
    t1 = t2;
    t2 = t;
}

Can someone identify and explain my mistake?

question from:https://stackoverflow.com/questions/65897567/why-doesnt-this-swapping-function-work-swapping-strings-in-c

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

C is strictly pass by value. You pass the values of ptsr[0] and pstr[1] to swap. It swaps where it keeps those two values, but that has no effect on the calling function. Consider:

swap (int v1, int v2)
{
    int t;
    t = v1;
    v1 = v2;
    v2 = t;
}

This is the same as your swap function, just using int instead. It should be pretty clear that if you call swap(1,2);, the swap function just puts the 2 where it was storing the 1 and vice versa, but that has no effect on anything in the caller.

Same if you do this:

int i = 2;
int j = 3;
swap(i,j);

Since all you passed to swap is the values 2 and 3, it cannot affect the values of i and j by any means.

And same with your swap function if you do this:

char* j = "hello";
char* k = "world";
swap(j,k);

The function receives "hello" and "world" and swaps where it stores those two pointers. This has no effect on j or k in the caller.

C is strictly pass by value. Whatever parameters you pass to a function, the function only receives the values of.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...