swap函数陷阱

使用c实现一个交换两个数的函数,代码很简单:

void swap(int *a, int *b)
{
*a ^= *b;
*b ^= *a;
*a ^= *b;
}

只有3行代码,且没有引入中间变量,使用了位运算,效率高!

但一个明显的缺陷是没有检查空指针,于是代码修正为:

void swap(int *a, int *b)
{
if (a == NULL || b == NULL)
return;
*a ^= *b;
*b ^= *a;
*a ^= *b;
}

似乎这样就完美了?

看看以下代码:

static int count = 0;
void permutation(int *a, int from, int to)
{
if (from == to) {
cout << ++count << ":";
for (int i = 0; i <= to; ++i)
cout << a[i] << " ";
cout << endl;
return;
}
for (int i = from; i <= to; ++i) {
swap(&a[from], &a[i]);
permutation(a, from + 1, to);
swap(&a[from], &a[i]);
}
}

以上代码功能很简单,使用递归的方式输出数组的全排列,核心算法肯定是没有问题的。可是运行以上代码,输出大量的0!!

why ?

答案在于swap函数还没有考虑当a,b是同一个指针的情况,当a == b时, *a ^= *b,结果必然为0,因此结果为*a == *b == 0,

因此正确的swap函数应该是这样的:

void swap(int* a, int* b)
{
if (a == NULL || b == NULL || a == b)
return;
*a ^= *b;
*b ^= *a;
*a ^= *b;
}

最新文章

  1. jar包目录下MANIFEST.MF标准格式
  2. Python基础教程【读书笔记】 - 2016/8/3
  3. org.hibernate.id.IdentifierGenerationException: Unknown integral data type for ids : java.lang.String
  4. [Everyday Mathematics]20150218
  5. C++ 临时对象
  6. 动作-CCActionInterval之CCAnimation&CCAnimate
  7. 【转】android官方侧滑菜单DrawerLayout详解
  8. linux shell 正则表达式(BREs,EREs,PREs)差异比较
  9. 腾讯课堂web零基础
  10. js控制表格实时编辑
  11. 全文检索Lucene (2)
  12. 前端可视化项目流程,涉及three.js(webGL),3DMax技术,持续更新
  13. The account that is running SQL Server Setup does not have one or all of the following rights: the right to back up files and directories, the right to manage auditing and the security log and the rig
  14. RBS SharePoint 2010 Server.wmv
  15. 手动部署etcd-2018-0731
  16. 廖雪峰Java5集合-3Map-Properties的使用
  17. bzoj千题计划209:bzoj1185: [HNOI2007]最小矩形覆盖
  18. 深入浅出Java垃圾回收机制(一)(转载)
  19. [原][osgearth]API加载earth文件的解析
  20. Python 的十个自然语言处理工具

热门文章

  1. Vue学习笔记【20】——Vue中的动画(使用动画钩子函数)
  2. 【NOI2011】兔农(循环节)
  3. jdk环境配置-windows 10
  4. BZOJ 4516: [Sdoi2016]生成魔咒(后缀数组)
  5. CSS中各种百分比(%)
  6. robotframework 时间控件的操作的几种方法总结。
  7. I/O复用 poll简介
  8. 树莓派安装omv
  9. Linux之mysql-redis-python使用
  10. samba环境部署