赞
踩
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
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。