void swap(int p1,int p2) //定义swap函数 { int temp; }
时间: 2023-12-13 11:03:22 浏览: 61
你定义的`swap`函数中缺少了实现交换两个变量值的代码。在你提供的代码中,`temp`变量没有被使用,也没有将`p1`和`p2`的值进行交换。
下面是一个完整的交换两个变量值的示例代码:
```c
void swap(int* p1, int* p2) {
int temp = *p1;
*p1 = *p2;
*p2 = temp;
}
```
在这个示例中,我们使用指针作为函数参数,通过指针来操作变量的值。`p1`和`p2`是指向整型变量的指针。我们使用一个临时变量`temp`来保存`p1`指向的值,然后将`p2`指向的值赋给`p1`,最后将`temp`的值赋给`p2`,实现了两个变量值的交换。
希望这能帮助到你。如果还有其他问题,请随时提问。
相关问题
void swap(int *p1,int *p2) //定义swap函数 { int *temp; *temp=*p1; *p1=*p2; *p2=*temp; } 为什么这个不对
你提供的代码有一个问题,即`temp`指针没有被正确初始化。在执行`*temp = *p1;`这行代码时,由于`temp`指针没有指向任何有效的内存位置,会导致未定义的行为。
为了修正这个问题,你需要为`temp`指针分配内存空间,或者使用一个已经存在的变量来作为中间变量。下面是两种修正的方法:
1. 使用已经存在的变量作为中间变量:
```c
void swap(int *p1, int *p2) {
int temp = *p1;
*p1 = *p2;
*p2 = temp;
}
```
2. 分配内存空间给`temp`指针:
```c
void swap(int *p1, int *p2) {
int *temp = (int*)malloc(sizeof(int));
*temp = *p1;
*p1 = *p2;
*p2 = *temp;
free(temp); // 释放内存空间
}
```
这两种修正方法都可以正确地交换两个指针所指向的值。
希望能够帮助到你。如果还有其他问题,请随时提问。
//(1)完成change(int * p1,int * p2)// //(2)实现2个参数交换数值// /********** Begin *********/
### 实现通过指针交换两个整数值的函数
为了实现一个能够通过指针交换两个整数值得到函数,在C/C++中定义如下所示的一个`swap`函数。此函数接收两个指向整型数据的指针作为参数,并利用临时变量存储其中一个值以便完成交换操作。
```cpp
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
```
上述代码展示了如何创建一个简单的交换函数[^1]。这里的关键在于理解传递给函数的是地址而非实际值,因此可以直接解引用这些指针改变原始位置处的数据。
下面给出完整的示例程序用于测试这个`swap`函数:
```cpp
#include <iostream>
// 定义交换函数
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
int main() {
int num1 = 5, num2 = 10;
std::cout << "Before swapping: num1 = " << num1 << ", num2 = " << num2 << '\n';
// 调用交换函数并传入两者的地址
swap(&num1, &num2);
std::cout << "After swapping: num1 = " << num1 << ", num2 = " << num2 << '\n';
return 0;
}
```
这段代码首先包含了必要的头文件<iostream>以支持输入输出流的操作。接着实现了之前提到过的`swap`函数,并在一个名为main的入口点内进行了两次打印——一次是在调用了带有两个整数地址作为实参的`swap`函数之前,另一次则在其之后显示了成功互换了它们的内容。
阅读全文
相关推荐
















