如何解决使用函数交换两个变量的值时,为什么要定位地址而不是实际变量名称?
我对 C 编程还很陌生,我不明白为什么在使用函数时交换两个变量的值不应该与不使用指针的正常方式相同。
#include <stdio.h>
void swap(int*,int*); //Swap function declaration
int main()
{
int x,y;
printf("Enter the value of x and y\n");
scanf("%d%d",&x,&y);
printf("Before Swapping\nx = %d\ny = %d\n",x,y);
swap(&x,&y);
printf("After Swapping\nx = %d\ny = %d\n",y);
return 0;
}
//Swap function definition
void swap(int *a,int *b)
{
int t;
t = *b;
*b = *a;
*a = t;
}
为什么不应该只是:
t = b;
b = a;
a = t;
解决方法
b = a
将 a 的值复制到 b。
*b = *a
将 a 指向的内存中的值复制到 b 指向的内存中。
当 a 和 b 是 int *
时,它们包含一个整数的内存地址,一个指针。在这种情况下,b = a
只会让 b 指向与 a 相同的内存。 *b
表示“取消引用” b 并使用它指向的值。所以 *b = *a
表示将 a 指向的值复制到 b 指向的内存中。
这一切都是必要的,因为您正在一个与其余代码隔离的函数中工作。该函数想要更改其作用域之外的两个变量的值,因此必须通过操作它们的内存来实现。
int *a,int *b
就像有两个名为 a 和 b 的桶。 b = a
使桶 a 和 b 相同。 *b = *a
将桶 a 中的内容复制到桶 b 中。 swap
想要交换 x 和 y 的存储桶中的内容。
您是否像这样通过值传递...
swap(x,y);
void swap(int a,int b)
{
int t;
t = b;
b = a;
a = t;
}
x 和 y 的值将复制到 a 和 b。 a 和 b 的值将交换对 x 和 y 没有影响。
你是否传递了指针,但没有取消引用,就像这样......
swap(&x,&y);
void swap(int *a,int *b)
{
int *t;
t = b;
b = a;
a = t;
}
现在 x 和 y 的内存地址复制到 a 和 b。 a 指向与 x 相同的内存,b 指向与 y 相同的内存。但是 b = a
在 a 和 b 之间交换这些地址对 x 和 y 没有影响。
swap(&x,int *b)
{
int t;
t = *b;
*b = *a;
*a = t;
}
x 和 y 的内存地址仍然复制到 a 和 b 中。 a 有 x 的地址,b 有 y 的地址。 *b = *a
改变它们指向的内存的值,与 y 和 x 相同。它实际上是 y = x
。 x 和 y 看到了变化。
考虑下面的程序
#include <stdio.h>
void f( int x )
{
x = 20;
printf( "Within f( int ) x = %d\n",x );
}
int main(void)
{
int x = 10;
printf( "Before call of f( int ) x = %d\n",x );
f( x );
printf( "After call of f( int ) x = %d\n",x );
return 0;
}
程序输出为
Before call of f( int ) x = 10
Within f( int ) x = 20
After call of f( int ) x = 10
如您所见,在 main 中声明的变量 x
并未通过调用该函数进行更改。
变量 x
已按值传递给函数 f
。即函数参数 x
(另一个具有功能块作用域的变量)由 main 中声明的变量 x
的值初始化。
所以函数改变了它的局部变量(参数)x
。 main 中声明的变量 x
保持不变。
您可以想象函数定义及其调用方式如下
f( x );
//...
void f( /*int parameter_x*/ )
{
int parameter_x = x;
patameter_x = 20;
printf( "Within f( int ) patameter_x = %d\n",patameter_x );
}
要更改 main 中声明的变量 x
,您必须通过引用传递它。
在 C 中,通过引用传递意味着通过指向对象的指针间接传递对象。
这是一个演示程序。
#include <stdio.h>
void f( int *px )
{
*px = 20;
printf( "Within f( int ) x = %d\n",*px );
}
int main(void)
{
int x = 10;
printf( "Before call of f( int ) x = %d\n",x );
f( &x );
printf( "After call of f( int ) x = %d\n",x );
return 0;
}
程序输出为
Before call of f( int ) x = 10
Within f( int ) x = 20
After call of f( int ) x = 20
取消引用指针 px
*px = 20;
该函数可以直接访问指向的对象,该对象指向 main 中声明的对象 x
。
所以如果你想在像 swap
这样的函数中交换 main 中声明的两个变量的值,你需要通过对函数的引用传递相应的对象。否则,该函数将处理 main 中声明的变量值的副本。
从欺骗中抽象出这种交换是没有意义的。使用宏:
#define SWAP(a,b,type) do{type c__c__c; c__c__c = (a); (a) = (b); (b) = c__c__c;}while(0)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。