c实现swap函数陷阱
2024-09-02 15:33:05
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;
}
最新文章
- jar包目录下MANIFEST.MF标准格式
- Python基础教程【读书笔记】 - 2016/8/3
- org.hibernate.id.IdentifierGenerationException: Unknown integral data type for ids : java.lang.String
- [Everyday Mathematics]20150218
- C++ 临时对象
- 动作-CCActionInterval之CCAnimation&CCAnimate
- 【转】android官方侧滑菜单DrawerLayout详解
- linux shell 正则表达式(BREs,EREs,PREs)差异比较
- 腾讯课堂web零基础
- js控制表格实时编辑
- 全文检索Lucene (2)
- 前端可视化项目流程,涉及three.js(webGL),3DMax技术,持续更新
- 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
- RBS SharePoint 2010 Server.wmv
- 手动部署etcd-2018-0731
- 廖雪峰Java5集合-3Map-Properties的使用
- bzoj千题计划209:bzoj1185: [HNOI2007]最小矩形覆盖
- 深入浅出Java垃圾回收机制(一)(转载)
- [原][osgearth]API加载earth文件的解析
- Python 的十个自然语言处理工具