简体   繁体   中英

how to swap two structs in C

I was looking at a code , written in C that swaps places of wto numbers and then two structs. I couldn't understand the second one :

#define SWAP(a,b) do {NODE *t = (a) ; (a) = (b) ; (b) = t;}

why does it work?? when I declare the t pointer of some struct "Node" so I directly point on a , then all data from b is being transfered to a , and b points to a as well... so I get that they both point on the same object(struct) .

If I write : Node t = *a instead , shouldn't it make it work? or i'm mistaken..

thanks!!

In this particular case, you are not transferring any data between the structures. You are just working on pointers which hold the addresses of the structures.

First, you create a pointer t which starts to point to whatever a was pointing to. Then, you modify pointer a so that it points to whatever b was pointing to. And finally, you modify b to point to whatever t is pointing to or IOW to what a was pointing before.

So, to sum up: you aren't moving any data between the structures *a and *b (where * means dereferencing the pointer) but just swapping the pointers a and b .

This code implies that both a and b are pointers of type NODE * . Suppose the two structs are the following: realA is a struct of type NODE and is pointed to by a; realB is also of type NODE and is pointed to by b. Now when you write this:

NODE *t = a;

here the temporary variable t, being a pointer and assigned to a, points to realA. Now when you see

a = b;

a no longer points to realA, but gets the address stored in b, so now a points to realB. And finally and similarily,

b = t;

infers that now b gets the pointer stored in t, which is, in turn, the address of realA.

All in all, only the pointers' contents have been changed; the actual data was untouched.

显而易见的猜测是,它们不会交换指针指向的东西,而只是交换指针本身。

This code swaps two pointers and doesn't copy any other data. It seems like a bad macro name; SWAP_NODE_PTR would be better.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM