如何不使用指针就交换整数?

如何解决如何不使用指针就交换整数?

#include <stdlib.h>
int swap(int a,int b);
int main() {
    int x,y;
    printf("Enter the first integer:"); scanf("%d",&x);
    printf("Enter the second integer:"); scanf("%d",&y);
    printf("\nBefore swap: x=%d,y=%d\n",x,y);
    swap(x,y);
    printf("After swap: x=%d,y=%d",y);
    
    return 0;
}

int swap(int a,int b){
        int temp;
        temp = a;
        a=b;
        b=temp;
}

这是我的代码,用于交换用户输入的2个整数,但是尽管一切似乎都井然有序,但是它不起作用。但是,如果我使用指针将代码更改为此,则可以。

#include <stdlib.h>

int swap(int *,int *);
int main() {
    int x,y);
    swap(&x,&y);
    printf("After swap: x=%d,y);
    
    return 0;
}

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

如果有人能向我解释为什么以及如何使用指针,但是为什么没有指针,我将不胜感激。

解决方法

C使用称为pass-by-value的东西。 基本上,这里发生的是所调用的函数(在本例中为await channel2.send(message.content))对您调用该函数时传递的参数进行自己的复制。 因此,在swap()函数中修改这些参数的值,即ab时,您仅在swap()函数中修改了它们的值,因为{ {1}}制作了自己的参数副本。

尝试这个比喻: 您错过了一些讲座,并拿了朋友的笔记本来更新笔记。现在,假设您对自己的笔记进行了一些更改。这些更改会延续到您朋友的笔记本上吗?显然不是。同样,当使用值传递时,对一个功能所做的更改不会超出该功能范围。

但是,当您使用指针时,值是通过引用传递的,也就是说,不是传递值,而是传递保存这些值的内存位置的地址。因此,如果您通过使用指针自己对这些存储位置进行更改,则这些值将永久更改,并且更改也将反映在调用者函数中。

,

第一个函数的返回类型为void,因为它什么也不返回

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

使用表达式值的副本作为参数进行交易。

您可以通过以下方式想象函数定义及其调用

swap(x,y);

//...

void swap( /* int a,int b */){
        int a = x;
        int b = y;
        int temp;
        temp = a;
        a=b;
        b=temp;
}

在函数内,交换了函数局部变量ab。在main中声明的原始变量xy保持不变。

在第二个函数定义中,参数xy通过引用传递给函数

swap(&x,&y);

在C中,按引用传递意味着通过对象的指针间接传递对象。

根据C标准(6.2.5类型,第20页)

-指针类型可以从函数类型或对象派生 类型,称为引用类型。 指针类型描述了一个对象 其值提供对所引用实体的引用 类型。有时,从引用类型T派生的指针类型是 称为“ T的指针”。从一个指针类型的构造 引用的类型称为“指针类型派生”。指针类型 是完整的对象类型。

因此,取消引用指针(它们本身通过值传递),您可以直接访问在函数中更改的指向对象

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

在C中,每个函数参数均按值传递。这意味着在函数范围内,每个参数只是传递给函数的实际变量的独立副本。通过将两个整数而不是它们的内存地址传递给函数来交换两个整数是不可能的,因为在函数体内交换的值不再与原始“外部”变量有任何联系,除了具有相同的值。

但是,没有功能,很有可能做您想做的事情:

#include <stdlib.h>

int main() {
    int x,y,temp;
    printf("Enter the first integer:"); scanf("%d",&x);
    printf("Enter the second integer:"); scanf("%d",&y);
    printf("\nBefore swap: x=%d,y=%d\n",x,y);
    temp=x;
    x=y;
    y=temp;
    printf("After swap: x=%d,y=%d",y);
    
    return 0;
}

或者,您可以编写一个方便的宏来为您完成此操作。它将以类似于函数的方式运行:

#include <stdlib.h>

#define swap(x,y) do { \
    int temp=x; \
    x=y; \
    y=temp; \
    } while (0)

int main() {
    int x,y);
    swap(x,y);
    printf("After swap: x=%d,y);
    
    return 0;
}

这有效并且非常优雅,但是请注意,它不是一个函数,以这种方式使用宏可能会导致失败。

,

我建议您查看一下Google的按引用传递和按值传递之间的区别,但我将在此处进行总结。

按值传递是当您直接给函数赋值时,此值在调用时被复制到函数的作用域中。 通过引用传递是在您传递指针到变量的同时,而不是传递变量的值。

例如:

void foo_by_value(int i) {
    // i is now stored in the int in the function's scope,it is not in any way affiliated with the variable or constant used to call the function
    
    i++; // This will only update the value of i inside this function
}

void foo_by_reference(int* i) {
    // i now holds the value of the memory address to an int. You are passing the pointer by value to obtain the variable by reference

    (*i)++; // This will update the value of the variable passed to the function
}

希望可以帮助清除一些东西!

,

您也可以为此使用宏

#define SWAP(type,y) do {type t_e_m_p___ = (x);(x) = (y); (y) = t_e_m_p___;} while(0)

int main(void)
{
    double d1 = 5.9,d2 = 7.4;
    SWAP(double,d1,d2);
    printf("Swapped: %f,%f\n",d2);
}

不需要指针

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 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-