我最近一直在研究C语言中的指针,我似乎无法完全理解这段代码:
int *ptr= (*int) 99999;
*ptr = 10;
printf("%dn,*ptr); //Outputs: 10
printf("%pn",&ptr); //Outputs: 0029FF14
printf("%pn",ptr); //Outputs: 0001869F
问题?
- "&ptr=
- 0029FF14"是存储"*ptr=10"的内存位置吗? "ptr=
- 0001869F"是存储"&ptr=0029FF14"的内存位置吗?如果不是,那么什么是ptr?
谢谢!
我相信这个问题与"C 指针语法"帖子不同,因为它不区分 ptr、*ptr 和 &ptr,这意味着该帖子没有解释为什么"ptr"根据它附带的运算符包含不同的值。[已编辑]
-
ptr
是指针本身。 -
*ptr
是它指向的值。 -
&ptr
是指针的地址。
所以欠条,
-
&a
是存储a
的内存位置。 -
a
是存储*a
的内存位置。
让我们修复一些问题:
int *ptr= (*int) 99999;
*ptr = 10;
除非你知道自己在做什么,否则永远不要这样做(你正在玩弄电锯)
相反,让我们做一个真正的 int 并使用它。
int test_int = 10;
int *ptr = &test_int;
printf("%dn",*ptr); //Outputs: 10
printf("%dn",test_int); //Outputs: 10 too
printf("%pn",&ptr); //Outputs: the location of ptr - its address
printf("%pn",ptr); //Outputs: the location of test_int
printf("%pn",&test_int); //Outputs: the location of test_int too