当前位置:   article > 正文

C语言中交换两个指针变量所指向的值_交两个指针变量的值

交两个指针变量的值
C语言中,指针变量有一级指针*p和二级指针**p,下面是使用指针交换两个变量的值。

1、使用一级指针交换:

#include "stdafx.h"
#include<stdio.h>

void swap(int* pt1,int* pt2){
int tmp;
//交换前的信息
printf("pt1 = %p\n",pt1);
printf("pt2 = %p\n",pt2);
printf("*pt1 = %d\n",*pt1);
printf("*pt2 = %d\n",*pt2);

//使用临时变量实现个数值的交换
tmp = *pt1;
*pt1 = *pt2;
*pt2 = tmp;

//输出交换后的信息
printf("*pt1 = %d\n",*pt1);
printf("*pt2 = %d\n",*pt2);
}
int main(int argc, char* argv[])
{
int a=5,b=55;
int* p1 = &a;
int* p2 = &b;

//swap函数调用前的信息
printf("p1 = %p\n",p1);
printf("p2 = %p\n",p2);
printf("*p1 = %d\n",*p1);
printf("*p2 = %d\n",*p2);

swap(p1,p2);

//输出函数调用后的信息
printf("*p1 = %d\n",*p1);
printf("*p2 = %d\n",*p2);


// printf("Hello World!\n");
return 0;
}

运行后结果如下:

p1=0018FF44

p2=0018FF40

*p1 = 5

*p2=55

pt1=0018FF44

pt2=0018FF40

*pt1=5

*pt2=55

*pt1=55

*pt2=5

*p1=55

*p2=5

使用一级指针改变的是变量的值,并不可改变指针所指向的地址。若用一级指针改变,只能将函数里面的局部的值所改变,也就是指将实参复制给了形参,并没有改变变量的值,实验代码如下:

// test1.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
int swap(int* p,int* q);
int main(int argc, char* argv[])
{
printf("Hello World!\n");
int a = 8;
int b = 88;

int* p = &a;
int* q = &b;

printf("交换前:\n");

printf("a=%d\n",*p);
printf("b=%d\n",*q);

printf("&a=%p\n",p);
printf("&b=%p\n",q);

swap(p,q);

printf("交换后:\n");

printf("a=%d\n",*p);
printf("b=%d\n",*q);

printf("&a = %p\n",p);
printf("&b = %p\n",q);

return 0;
}
int swap(int* p,int* q){
int* temp;
temp = p;
p = q;
q = temp;

printf("函数中交换后:\n");
printf("&a = %p\n",p);
printf("&b = %p\n",q);
printf("a=%d\n",*p);
printf("b=%d\n",*q);
return *p,*q;
}

结果如下 :

交换前:

a = 8

b = 88

&a = 0018FF44

&b = 0018FF40

函数中交换后:

&a = 0018FF40

&b = 0018FF44

a = 88

b = 8

交换后:

a=8

b=88

&a = 0018FF44

&b = 0018FF40

2、使用二级指针交换:

#include "stdafx.h"

int jh(int** x,int** y);
int main(int argc, char* argv[])
{
printf("Hello World!\n");
int a = 8;
int b = 88;

int* p = &a;
int* q = &b;

int** pp = &p;
int** qq = &q;

printf("a=%d\n",*p);
printf("b=%d\n",*q);

printf("&a=%p\n",p);
printf("&b=%p\n",q);

jh(pp,qq);
printf("a=%d\n",*p);
printf("b=%d\n",*q);

printf("&a=%p\n",p);
printf("&b=%p\n",q);

return 0;
}

int jh(int**x,int**y){
int* temp;
temp = *x;
*x = *y;
*y = temp;


printf("%&a=p\n",*x);
printf("%&b=p\n",*y);
printf("a=%d\n",**x);
printf("b=%d\n",**y); return **x,**y;

}

运行结果如下:

a=8

b=88

&a=0018FF44

&b=0018FF40

函数中:

a=88

b=8

&a=0018FF40

&b=0018FF44

交换后:

a=88

b=8

&a=0018FF40

&b=0018FF44

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/思考机器5/article/detail/63016
推荐阅读
相关标签
  

闽ICP备14008679号