【发布时间】:2014-01-24 14:12:09
【问题描述】:
#include <stdio.h>
#include <string.h>
void swap(int *p1, int *p2)
{
int *temp;
temp=p1;
p1=p2;
p2=temp;
}
main()
{
int n1=10,n2=20;
printf("%d,%d\n",n1++,++n2);
swap(&n1,&n2);
printf("%d,%d",++n1,n2++);
}
当我运行此代码时,输出为 10,21 和 12,21。我的问题是为什么 N1 和 N2 的值没有交换?由于函数交换使用指针并且方法是通过引用调用的,它们不应该交换吗?还是我错过了一些概念?提前致谢
【问题讨论】:
-
如果你想实现引用语义,你需要在你的被调用者的某个点dereference。