介绍
在本实验中,我们将学习如何在 C++ 中使用指针交换两个数字。该程序通过将两个数字的地址传递给函数,并使用指针指向它们在内存中的位置来实现交换。
包含头文件并声明函数
首先,我们包含必要的头文件,并声明一个接受两个整数指针作为参数的 swap 函数。
#include <iostream>
using namespace std;
//Swap function to swap 2 numbers
void swap(int *num1, int *num2);
定义 swap 函数
在这里,我们按如下方式实现 swap 函数:
void swap(int *num1, int *num2) {
int temp;
//Copy the value of num1 to some temp variable
temp = *num1;
//Copy the value of num2 to num1
*num1 = *num2;
//Copy the value of num1 stored in temp to num2
*num2 = temp;
}
该函数接受两个整数指针作为参数,并使用一个临时变量交换它们所指向的值。
输入两个数字并调用 swap 函数
声明 num1 和 num2 变量,并使用 cin 输入它们的值。调用 swap 函数并传入它们的地址作为参数。
int main() {
int num1, num2;
//Inputting 2 numbers from user
cout<<"Enter the first number : ";
cin>>num1;
cout<<"Enter the Second number : ";
cin>>num2;
//Passing the addresses of num1 and num2
swap(&num1, &num2);
输出交换后的数字
使用 cout 输出交换后的数字。
//Printing the swapped values of num1 and num2
cout<<"First number : "<< num1 << endl;
cout<<"Second number: "<<num2 << endl;
编译并运行程序
将程序保存到 ~/project 目录下,文件名为 main.cpp。使用以下命令编译代码:
g++ main.cpp -o main && ./main
总结
在本实验中,我们学习了如何在 C++ 中使用指针交换两个数字。我们声明并定义了一个 swap 函数,用于交换两个整数指针所指向的值,并使用 cin 和 cout 分别获取用户输入和显示输出。



