简体   繁体   English

如何在C中交换两个结构

[英]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. 我正在查看一个用C语言编写的代码,该代码交换了wto数字的位置,然后是两个结构。 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) . 当我声明一些结构“节点”的t指针,所以我直接指向a,然后b中的所有数据都被转移到a,而b指向a ...所以我得到它们都指向同一个object(struct)。

If I write : Node t = *a instead , shouldn't it make it work? 如果我写: Node t = *a相反,它不应该使它工作? 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. 首先,创建一个指针t其开始指向任何a被指向。 Then, you modify pointer a so that it points to whatever b was pointing to. 然后,修改指针a ,使其指向b指向的任何内容。 And finally, you modify b to point to whatever t is pointing to or IOW to what a was pointing before. 最后,您修改b指向任何t指向或IOW到什么a指着面前。

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 . 所以,总结一下:你没有在结构*a*b之间移动任何数据(其中*表示取消引用指针),而只是交换指针ab

This code implies that both a and b are pointers of type NODE * . 此代码表示a和b都是NODE *类型的指针。 Suppose the two structs are the following: realA is a struct of type NODE and is pointed to by a; 假设两个结构如下:realA是NODE类型的结构,由a指向; realB is also of type NODE and is pointed to by b. realB也是NODE类型,由b指向。 Now when you write this: 现在当你写这个:

NODE *t = a;

here the temporary variable t, being a pointer and assigned to a, points to realA. 这里临时变量t是一个指针,分配给a,指向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. a不再指向realA,而是获取存储在b中的地址,所以现在指向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. 推断现在b得到的指针存储在t中,而t又是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. SWAP_NODE_PTR会更好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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