使用函数交换两个变量的值时,为什么要定位地址而不是实际变量名称?

如何解决使用函数交换两个变量的值时,为什么要定位地址而不是实际变量名称?

我对 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 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-