用C交换指针 [英] Swapping pointer in C
本文介绍了用C交换指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
#包括LT&;&stdio.h中GT;
无效之谜(INT * PTRA,为int *的ptrB){
INT *温度;
TEMP =的ptrB;
的ptrB =成形术;
PTRA =温度;
}
诠释主(){
诠释一个= 2016年,B = 0,C = 4,D = 42;
谜(安培;一,和b);
如果(一个c为C)
谜(和C,和放大器;一个);
谜(安培;一,和D);
打印F(%d个\\ N,一);
}
我尝试:
A和D是不交换的功能之谜()不会改变值,但三分球这是本地的功能。
你能在正式的方式解释,请。如何运作功能
之谜
?
块引用>解决方案
A和D是不交换的功能之谜()不会改变值,但三分球这是本地的功能。
块引用>是的,你是对的。功能
之谜
不交换值。它只是换指针PTRA
和的ptrB
由的ptrB $ C指出的位置
PTRA
分别为$ C>和。A
+ -------------- +
| |
PTRA ----------> | 2016年|
| |
+ -------------- + b
+ -------------- +
| |
----------的ptrB GT&; | 0 |
| |
+ -------------- +执行语句后
TEMP =的ptrB;
的ptrB =成形术;
PTRA =温度; 一个
+ -------------- +
| |
PTRA ----- + | 2016年|
+ ------> | |
| | + -------------- +
| |
| |
| |
| | b
| | + -------------- +
| | | |
---的ptrB + ----> | 0 |
| |
+ -------------- +# include <stdio.h> void mystery (int *ptra, int *ptrb) { int *temp; temp = ptrb; ptrb =ptra; ptra = temp; } int main () { int a = 2016, b=0, c= 4, d = 42; mystery (&a, &b); if (a < c) mystery (&c, &a); mystery (&a, &d); print f("%d\n", a); }
My attempt :
a and d are not swapped as the function mystery() doesn’t change values, but pointers which are local to the function.
Can you explain in formal way, please. how works function
mystery
?
解决方案a and d are not swapped as the function mystery() doesn’t change values, but pointers which are local to the function.
Yes, you are right. Function
mystery
is not swapping values. It is just swapping the pointerptra
andptrb
to location pointed byptrb
andptra
respectively.a +--------------+ | | ptra ----------> | 2016 | | | +--------------+ b +--------------+ | | ptrb ----------> | 0 | | | +--------------+
After executing statements
temp = ptrb; ptrb =ptra; ptra = temp; a +--------------+ | | ptra -----+ | 2016 | +------> | | | | +--------------+ | | | | | | | | b | | +--------------+ | | | | ptrb ---+ +----> | 0 | | | +--------------+
这篇关于用C交换指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文