一个内存数据交换的例子(一)
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本身存储的内存地址值,而不是它们所指向的对象的值,这是不同于调用方式一的地方
调用方式二:
相关文章推荐
- IE7降低内存和降低CPU的几个技巧
- 如何高效的使用内存
- DOS下内存的配置
- XP/win2003下发现1G的内存比512M还慢的解决方法
- PowerShell实现动态获取当前脚本运行时消耗的内存
- C#实现把dgv里的数据完整的复制到一张内存表的方法
- SQL语句实现查询SQL Server内存使用状况
- C语言内存对齐实例详解
- 深入学习C语言中memset()函数的用法
- 全局变量与局部变量在内存中的区别详细解析
- VB读取线程、句柄及写入内存的API代码实例
- php运行提示:Fatal error Allowed memory size内存不足的解决方法
- IE浏览器IFrame对象内存不释放问题解决方法
- C#之CLR内存深入分析
- JavaScript 变量、作用域及内存
- JavaScript避免内存泄露及内存管理技巧
- J2ME编程中的几个重要概念介绍
- c++实现逐行读取配置文件写入内存的示例
- Shell脚本查看进程内存真实占用情况
- w3wp.exe占用cpu过高的解决方法第1/2页