C中使用指向字符指针的通用交换函数
我不太明白这段代码是如何工作的:C中使用指向字符指针的通用交换函数,c,pointers,char,void-pointers,char-pointer,C,Pointers,Char,Void Pointers,Char Pointer,我不太明白这段代码是如何工作的: #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; } } in
#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个字节。
但最后,如何将char指针解引用到int值呢?让我们试着用代码注释一步一步地解决这个问题
#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);
}
因此,基本上,它通过检查任何给定的数据类型,重新解释为字节,然后交换字节来工作。gswap不是取消对int值的引用,它只是逐字节交换int的位模式。转换为字符*是一种用于获取对象的单个字节的技巧。@Pablo不会使用stdint.h,转换为uint8_t*可能更可读?@BernardoMeurer uint8_t会像无符号字符一样增加清晰度。但实际上并不需要。注意:uint8_t是一种可选类型,虽然很常见。@chux是的,我的意思主要是为了清楚,我从来不喜欢用char来表示字节:P