2016-03-11 223 views
-6

我最近一直在研究中的指针C,和我不能似乎完全理解此代码:差异,* PTR和&PTR

int *ptr= (*int) 99999; 
*ptr = 10; 
printf("%d\n,*ptr); //Outputs: 10 
printf("%p\n",&ptr); //Outputs: 0029FF14 
printf("%p\n",ptr); //Outputs: 0001869F 

问题?

  1. 是“& ptr = 0029FF14”存储“* ptr = 10”的存储位置吗?
  2. “ptr = 0001869F”是否存储“& ptr = 0029FF14”的存储位置?如果不是那么ptr是什么?

谢谢!

我相信这个问题不同于“C指针语法”后,因为它不区分ptr,* ptr和& ptr,这意味着帖子并没有解释为什么“ptr”包含不同的值,具体取决于它随附的操作员。 [EDITED]

+3

你为什么认为选择一个随机存储位置可以工作? aka这行''ptr = 10;' –

+1

该代码不会提供那些输出,实际上不会编译。 – OrangeDog

+0

@EdHeal这行不是问题。 'int * ptr =(* int)99999;'is。 – glglgl

回答

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

所以IOW,

  1. &a是其中a被存储的存储器位置。

  2. a是存储*a的存储位置。

2

让我们修复的几件事情:

int *ptr= (*int) 99999; 
*ptr = 10; 

永远不要做,除非你知道你在做什么(你是玩弄链锯)

反而让做一个真正的int和玩它。

int test_int = 10; 
int *ptr = &test_int; 
printf("%d\n",*ptr);  //Outputs: 10 
printf("%d\n",test_int); //Outputs: 10 too 
printf("%p\n",&ptr);  //Outputs: the location of ptr - its address 
printf("%p\n",ptr);  //Outputs: the location of test_int 
printf("%p\n",&test_int); //Outputs: the location of test_int too 
相关问题