[英]Trying to understand reference of and address of in pointers
給定下面的代碼,為什么a和b的值會發生變化。.P1和p2存儲a和b的地址,為什么當p1和p2發生變化時a和b也會發生變化
#include <stdio.h>
int main(int argc, char** argv)
{
//&a stores address
//*p1 is a pointer
int a = 5, b = 10;
int *p1, *p2; //p1 and p2 are 2 pointers which can store int addressses
p1 = &a; //now p1 and p2 stores address of a and b
p2 = &b;
printf("p1 storing address of a = %d\n", *p1);
printf("p2 storing address of b = %d\n", *p2);
*p1=30;
*p2=40;
printf("p1 assigning values to p1 pointer = %d\n", *p1);
printf("p2 assigning values to p2 pointer= %d\n", *p2);
printf("a whose value is = %d\n", a);
printf("b = %d\n", b);
}
我認為,如果您還自己打印指針而不是僅打印指針的內容,那么事情對您來說會更加清楚。 您可以使用%p
說明符。
#include <stdio.h>
int main()
{
int a = 10;
int b = 20;
int *p = &a;
int *q = &b;
printf("1) p is %p\n", p);
printf("1) q is %p\n", q);
printf("1) a is %d\n", a);
printf("1) b is %d\n", b);
p = q;
/* At this point, I changed the value of p so that it points to `b`
just like `q` does. `a` and `b` are still unchanged. */
printf("2) p is %p\n", p);
printf("2) q is %p\n", q);
printf("2) a is %d\n", a);
printf("2) b is %d\n", b);
*p = 30;
/* Now that p points to `b`, dereferencing the pointer will affect `b`
instead of `a` */
printf("3) p is %p\n", p);
printf("3) q is %p\n", q);
printf("3) a is %d\n", a);
printf("3) b is %d\n", b);
}
當您說*p = something
您正在分配p
指向的內存位置(根據設置方式的不同,可能是a
或b
)。 另一方面,如果執行p = q
,則將更改指針本身,而不是指針所指向的內容。
p1
和p2
包含地址a
和b
。 當我們使用*p1=30;
它告訴編譯器將p1
包含其地址的變量的值分配為30
您可以將其視為由p1
表示的地址值為30
。
* = value at
和
& = address of
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.