C++ 互换指针指向内存结果

1. 互换指针指向内存结果

将命令参数前两个值在主存中互换并输出。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include "mySwap.hpp"

int main(int argc, char** argv)
{
std::cout<<"Origin info is: "<<std::endl;
std::cout<<"a: "<<argv[1]<<" \tb: "<<argv[2]<<std::endl;
mySwap(argv[1],argv[2]);
std::cout<<"Has been swaped info is: "<<std::endl;
std::cout<<"a: "<<argv[1]<<" \tb: "<<argv[2]<<std::endl;

return 0;
}

1
2
3
4
5
6
7
8
void mySwap(char* &a,char*  &b)
{
char* temp;
temp = a;
a=b;
b=temp;
}

运行结果

结果1

2. 简单变量交换

下面提供了一个简单的变量互换代码。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include<iostream>
void swap(int &a,int &b)
{
int temp = a;
a= b;
b = temp;
}

int main()
{
int a,b;
std::cin>>a>>b;
std::cout<<"Original info is "<<std::endl;
std::cout<<"a: "<<a<<" b: "<<b<<std::endl;
swap(a,b);
std::cout<<"Has been swaped info is "<<std::endl;
std::cout<<"a: "<<a<<" b: "<<b<<std::endl;
return 0;
}

运行结果

结果2