需要帮助理解 c 中的指针
我无法理解指针概念,下面是代码。为什么 swap(&a1, &a2) 输出是 -5, 6 而不是 6, -5 ?这些值已经交换了,对吧?
void swap(int *ptr1, int *ptr2){
int temp;
temp = *ptr1;
*ptr1 = *ptr2;
*ptr2 = temp;
}
int main (int argc, char *argv[]){
void swap(int *ptr1, int *ptr2);
int a1 = -5;
int a2 = 6;
int *p1 = &a1;
int *p2 = &a2;
NSLog(@" a1 = %i, a2 =%i", a1, a2); // out puts: -5, 6
swap(p1,p2);
NSLog(@" a1 = %i, a2 =%i", a1, a2); // out puts: 6, -5
swap(&a1, &a2);
NSLog(@" a1 = %i, a2 =%i", a1, a2); // out puts: -5, 6
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
第一次调用 swap() 交换了两个值,第二次调用将它们交换回来。
Your first call to swap() swapped the two values, and the second call swapped them back.
你每次都会交换相同的东西(某种程度),所以首先你交换它们,然后再交换回来。
a1 在地址1处存储值-5(地址是内存中的一个位置)
a2 将值 6 存储在地址 2 处
p1指向addres1
p2指向地址2
交换p1和p2
在这里,您获取存储在地址 1 中的项目的值,并将其与地址 2 中的项目的值进行交换。
所以现在
地址 1 保存值 6,地址 2 保存值 -5
这里 p1 和 p2 仍然指向相同的地址,a1 和 a2 仍然从相同的地址返回值,但值已被交换。
交换 &a1 和 &a2
交换 &a1 和 &a2 会做同样的事情,&将地址作为指针返回,并将其传递给交换函数。 Swap 获取指针并交换它们指向的地址的值。
基本上,指针指向内存位置。您的交换函数获取内存位置并交换存储在其中的数据,它不会更改它们指向的内存地址。因此,在这两种情况下,您都发送相同的地址,因此您将相同的地址交换两次。
You are swapping the same thing every time(sorta) so first you swap them, and then you swap them back.
a1 stored the value -5 at address1 (an address is a location in memory)
a2 stores the value 6 at addess2
p1 points to addres1
p2 points to address2
swapping p1 and p2
Here you take the value of the item stored at address1 and switch it with the value of the item at address2.
so now
address1 holds the value 6 and address2 holds the value -5
Here p1 and p2 still point at the same addresses and a1 and a2 still return values from the same addresses but the values have been swapped.
swapping &a1 and &a2
Swapping &a1 and &a2 does the same thing, the & returns the addresses as pointers, which you them pass to the swap function. Swap takes to pointers and swaps the values of the addresses they point to.
Basically, pointers point to a memory location. Your swap function takes to memory locations and exchanges the data stored in them, it does not change what memory address they are pointing to. So in both cases you are sending the same addresses, so you swap the same to location twice.
一个非常简单的例子,只是为了了解指针...
p == q 是 true
*p == 2 是 true
*p == *q 是 true
i == 2 仍然是 true,无论你对指针做了什么变量
指针变量可以被视为或认为保存“特殊”整数值,它们存储内存地址,通常是 32 位数字(除非您在 64 位地址计算机上运行)。
A very simple example just to get a feeling about pointers...
p == q is true
*p == 2 is true
*p == *q is true
i == 2 is still true irrespective of what you did with your pointer variable
Pointer variables could be seen or thought of as holding "special" integer values, they store a memory address, which usually is 32-bit number (unless you are running on a 64-bit address computer).