c语言 - ptr,*ptr 和 &ptr 之间的区别



我最近一直在研究C语言中的指针,我似乎无法完全理解这段代码:

int *ptr= (*int) 99999;
*ptr = 10;
printf("%dn,*ptr);  //Outputs: 10
printf("%pn",&ptr); //Outputs: 0029FF14
printf("%pn",ptr);  //Outputs: 0001869F

问题?

    "&ptr=
  1. 0029FF14"是存储"*ptr=10"的内存位置吗?
  2. "ptr=
  3. 0001869F"是存储"&ptr=0029FF14"的内存位置吗?如果不是,那么什么是ptr?

谢谢!

我相信这个问题与"C 指针语法"帖子不同,因为它不区分 ptr、*ptr 和 &ptr,这意味着该帖子没有解释为什么"ptr"根据它附带的运算符包含不同的值。[已编辑]

  • ptr是指针本身。
  • *ptr是它指向的值。
  • &ptr是指针的地址。

所以欠条,

  1. &a是存储a的内存位置。

  2. 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

最新更新