zoukankan      html  css  js  c++  java
  • C#和C/C++指针实现swap交换

    当我们要编程的时候要实现两个数的简单交换,要求必须调用子函数来交换,咋一看挺简单,就直接交换一下或许就能实现,但真正实现起来或许我们会碰到一定的问题,当运行结果的时候,我们有可能会惊讶的发现怎么两个数还没有交换呢,其实这是我们对函数参数是值类型还是应用类型还不够了解,发生错误就是因为我们使用的是值传递,接下来我通过两种语言来实现这一方法,首先是c语言实现
    C代码实现:
    #include <stdio.h>
    
    void swap(int* a,int* b)
    {
    	int p;
    	p=*a;
    	*a=*b;
    	*b=p;
    }
    
    int main()
    {
    	int a=1;
    	int b=2;
    	printf("a=%d,b=%d",a,b);
    	swap(&a,&b);
    	printf("\na=%d,b=%d",a,b);
    	return 0;
    }
    
    其次是C#实现,很多初学者或许会疑惑,为什么C#是继C/C++/java之后的新的面向对象的语言,他取长补短,实现了很多的封装,让我们程序员使用起来非常的便捷,但为什么微软取消了C/C++中指针的实现,其实进一步升入,其实微软并没有抛弃这一类型,只不过是换了一种说法而已,用ref和out关键字取代了之前的指针,从而实现了地址的传递,接下来介绍一下C#实现的swap方法
    C#代码实现:
     
    using System;
    
    namespace Swap
    {
        class Program
        {
            public static void Main(string[] args)
            {
                int a = 2;
                int b = 3;
                Console.WriteLine("a={0},b={1}", a, b);
                Swap(ref a, ref b);
                Console.WriteLine("a={0},b={1}", a,b);
                Console.Read();
            }
    
            private static void Swap(ref int a, ref int b)
            {
                int p = a;
                a = b;
                b = p;
            }
        }
    }
    

    感谢来访,共同学习!
  • 相关阅读:
    VS2010 自动跳过代码现象
    Reverse Linked List II 【纠结逆序!!!】
    Intersection of Two Linked Lists
    Linked List Cycle II
    Remove Nth Node From End of List 【另一个技巧,指针的指针】
    Swap Nodes in Pairs
    Merge Two Sorted Lists
    Remove Duplicates from Sorted List
    Linked List Cycle
    Dungeon Game
  • 原文地址:https://www.cnblogs.com/dingxiaowei/p/3058830.html
Copyright © 2011-2022 走看看