您的位置:首页 > 其它

一个内存数据交换的例子(一)

2016-04-25 22:09 519 查看
#include <stdio.h>

void SWAP(void*vp1, void*vp2, int size);

int main(void)
{
char *husband = strdup("Fred");
char *wife = strdup("Wilma");
SWAP(husband, wife, sizeof(char*)); //调用方式一:这种交换方式为什么不行?
SWAP(&husband, &wife, sizeof(char*)); //调用方式二:这种交换方式为什么在指针类型数据交换时有效?
printf("husband: %s, wife: %s\n", husband,wife);

return 0;
}

void SWAP(void *vp1, void *vp2, int size)
{
char *buffer = (char*)malloc(sizeof(char)*size);
if (NULL == buffer) {
printf("内存分配失败!\n");
return;
}
memcpy(buffer, vp1, size);
memcpy(vp1, vp2, size);
memcpy(vp2, buffer, size);
free(buffer);
}


调用方式一:

husband : “Fred”

wife: “Wilma”

SWAP(husband, wife, sizeof(char*));


sizeof(char*)的值是4个字节(假设是32位系统),那么执行该操作之后,就只是交换 husband 和 wife 所指内存的4个字节数据而已,于是,husband: “Wilm

wife: “Fred**a”,注意这里,因为只是复制四个字节数据,因此,只是将wife中的前四个字节替换为**Fred,尾字母a保留

这里调用方式一,只是交换husband和wife所指向的值的四个字节内容

执行结果:



调用方式二:

husband : “Fred”

wife: “Wilma”

SWAP(&husband, &wife, sizeof(char*));


假设:ptr1为 &husband,ptr2为 &wife

ptr1 –> husband –> “Fred”

ptr2 –> wife –> “Wilma”

这里调用 SWAP函数,实际交换的是 husband和wife本身存储的内存地址值,而不是它们所指向的对象的值,这是不同于调用方式一的地方

调用方式二:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  内存