这些交换功能,为什么不同的表现? [英] Why do these swap functions behave differently?

查看:127
本文介绍了这些交换功能,为什么不同的表现?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 的#include<&stdio.h中GT;无效swap1(INT A,INT B)
{
    INT TEMP =一个;    A = B;
    B =温度;
}无效swap2为(int *一,为int * B)
{
    为int * TEMP = A;    A = B;
    B =温度;
}无效swap3为(int *一,为int * B)
{
    INT TEMP = *一个;    * A = * B;
    * B =温度;
}主要()
{
    诠释一个= 9,B = 4;    的printf(%D,%d个\\ N,A,B);
    swap1(A,B);
    的printf(%D,%d个\\ N,A,B);
    swap2(&放大器;一,和b);
    的printf(%D,%d个\\ N,A,B);
    swap3(&放大器;一,和b);
    的printf(%D,%d个\\ N,A,B);}


解决方案

C具有的值语义的函数参数。这意味着 A B 所有你的三个交换变种的局部变量的的各自的功能。值的他们的拷贝的你作为参数传递。换句话说:


  • swap1 两个局部整型变量的值交换 - 在函数外没有明显的效果

  • 两个局部变量,这是在这种情况下指针的
  • swap2 交流价值观 - 一样,没有明显的效果

  • swap3 终于得到它的权利和交换价值的指出的本地指针变量。

#include <stdio.h>

void swap1(int a, int b)
{
    int temp = a;

    a = b;
    b = temp;
}

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

    a = b;
    b = temp;
}

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

    *a = *b;
    *b = temp;
}

main()
{
    int a = 9, b = 4;

    printf("%d , %d\n", a, b);
    swap1(a, b);
    printf("%d , %d\n", a, b);
    swap2(&a, &b);
    printf("%d , %d\n", a, b);
    swap3(&a, &b);
    printf("%d , %d\n", a, b);

}

解决方案

C has value semantics for function parameters. This means the a and b for all your three swap variants are local variables of the respective functions. They are copies of the values you pass as arguments. In other words:

  • swap1 exchanges values of two local integer variables - no visible effect outside the function
  • swap2 exchanges values of two local variables, which are pointers in this case, - same, no visible effect
  • swap3 finally gets it right and exchanges the values pointed to by local pointer variables.

这篇关于这些交换功能,为什么不同的表现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆