Generic swap function using pointer to char in C
我不太明白这个代码是如何工作的:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | #include <stdio.h> void gswap(void* ptra, void* ptrb, int size) { char temp; char *pa = (char*)ptra; char *pb = (char*)ptrb; for (int i = 0 ; i < size ; i++) { temp = pa[i]; pa[i] = pb[i]; pb[i] = temp; } } int main() { int a=1, b=5; gswap(&a, &b, sizeof(int)); printf("%d , %d", a, b) } |
我理解char在内存中有1个字节(大小),我们使用指针交换int值的每个字节(4个字节)。但最后,如何才能取消对指向int值的char指针的引用呢?
让我们试着用代码注释一步一步地解决这个问题。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | #include <stdio.h> //gswap() takes two pointers, prta and ptrb, and the size of the data they point to void gswap(void* ptra, void* ptrb, int size) { // temp will be our temporary variable for exchanging the values char temp; // We reinterpret the pointers as char* (byte) pointers char *pa = (char*)ptra; char *pb = (char*)ptrb; // We loop over each byte of the type/structure ptra/b point too, i.e. we loop over size for (int i = 0 ; i < size ; i++) { temp = pa[i]; //store a in temp pa[i] = pb[i]; // replace a with b pb[i] = temp; // replace b with temp = old(a) } } int main() { // Two integers int a=1, b=5; // Swap them gswap(&a, &b, sizeof(int)); // See they've been swapped! printf("%d , %d", a, b); } |
所以,基本上,它通过遍历任何给定的数据类型、重新解释为字节以及交换字节来工作。