C/C++中函数的传值调用、指针调用、引用调用问题

23 篇文章 0 订阅

以swap函数来说明问题:

 

#include <stdio.h>
#include <iostream>

void swap1(int a, int b)//传值调用,不能达到交换的目的
{
    int temp;
    temp=a;
    a=b;
    b=temp;
    printf("a=%d,b=%d\n",a,b);
}

void swap2(int *a, int *b)//指针调用,能达到交换的目的
{
    int temp;
    temp=*a;
    *a=*b;
    *b=temp;
    printf("*a=%d,*b=%d\n",*a,*b);
}
void swap3(int &a, int &b)//引用调用,能达到交换的目的
{
    int temp;
    temp=a;
    a=b;
    b=temp;
    printf("a=%d,b=%d\n",a,b);
}

void swap4(int *a, int *b)
{
    int *temp;
    int c=5;
    temp=&c;

    *temp=*a;
    *a=*b;
    *b=*temp;
    printf("*a=%d,*b=%d\n",*a,*b);
}

void swap5(int *a, int *b)
{
    int *temp;
    temp=a;
    a=b;
    b=temp;
    printf("*a=%d,*b=%d\n",*a,*b);
}

int main()
{
    int i,j;

    i=3;j=4;
    printf("before swap1:i=%d,j=%d\n",i,j);
    swap1(i,j);
    printf("after swap1:i=%d,j=%d\n\n",i,j);

    i=3;j=4;
    printf("before swap2:i=%d,j=%d\n",i,j);
    swap2(&i,&j);
    printf("after swap2:i=%d,j=%d\n\n",i,j);

    i=3;j=4;
    printf("before swap3:i=%d,j=%d\n",i,j);
    swap3(i,j);
    printf("after swap3:i=%d,j=%d\n\n",i,j);

    i=3;j=4;
    printf("before swap4:i=%d,j=%d\n",i,j);
    swap4(&i,&j);
    printf("after swap4:i=%d,j=%d\n\n",i,j);

    i=3;j=4;
    printf("before swap5:i=%d,j=%d\n",i,j);
    swap5(&i,&j);
    printf("after swap5:i=%d,j=%d\n\n",i,j);

    return 0;
}

我们重点分析swap4 和swap5:

swap4实现了交换的目的,但要注意其与swap2的区别
void swap4(int *a, int *b)
{
    int *temp;
    int c=5;
    temp=&c;

    *temp=*a;
    *a=*b;
    *b=*temp;
    printf("*a=%d,*b=%d\n",*a,*b);
}

如果将swap4改为以下将会出现段错误:
void swap4(int *a, int *b)
{
    int *temp;

    *temp=*a;
    *a=*b;
    *b=*temp;
    printf("*a=%d,*b=%d\n",*a,*b);
}

因为这里定义int *temp;时,temp是个野指针,其没指向任何一个变量,当执行 *temp=*a;时将a所指内存的值赋给*temp,系统不知道放到哪里,所以产生错误。

 

swap5函数的内部实现了交换,将a指向了j,b指向了i,但i和j的值没有改变。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值