无法理解这个简单的代码输出

时间:2013-08-08 18:30:32

标签: c

代码:

int a = 5;
int *ptr;
ptr = &a;

printf("%d",*ptr);
printf("\n%d",*(ptr++));
printf("\n%d",(*ptr)++);
printf("\n%d",++(*ptr));

输出:

5
5
1638268
1638268

我希望输出为:     五     破烂     五     7 Sory,我的指针和运算符优先级概念非常暗淡。无法理解这个简单的输出。

4 个答案:

答案 0 :(得分:6)

  1. 第一个显然是5,只是解除引用指针
  2. 还有五个因为后缀运算符返回指针preincrement
  3. 3和4是垃圾,因为指针不再指向已分配的内存
  4. 如果您希望第二个按预期行事并打印垃圾,则可以使用前缀++代替

答案 1 :(得分:4)

int a = 5;
int *ptr;
ptr = &a;

printf("%d",*ptr);          // 5 as you expected.
printf("\n%d",*(ptr++));    // 5, because the pointer is incremented after this line
printf("\n%d",(*ptr)++);    // Not 5 because pointer points to another location.
printf("\n%d",++(*ptr));    // Pointer already changed, no longer pointing at 5.

答案 2 :(得分:3)

int a = 5;
int *ptr; 
ptr = &a;  // ptr is the address of the int 5

printf("%d",*ptr);  // dereferences ptr, which points to in 5
printf("\n%d",*(ptr++));  // increments ptr by one, so ptr not points to 
                          // an int one over from wherever int 5 is in memory
                          // but return ptr before incrementing and then dereference it
                          // giving int 5
printf("\n%d",(*ptr)++);  // dereference ptr, which is now one int over from 5 thanks
                          // to the last line, which is garbage, try 
                          // to increment garbage by 1 after printing
printf("\n%d",++(*ptr));  // dereference ptr, which is now one int over from 5, 
                          // try to increment garbage by one before printing

答案 3 :(得分:3)

*ptr只提供该位置的值,该值只是a的值。

由于发布增量,

*(ptr++)相当于(*ptr)然后(ptr += 1),所以首先它给出了printf使用的值,然后递增指针所以它现在指向垃圾记忆。

(*ptr)++相当于(*ptr),然后是(*ptr += 1),因此它会获取垃圾内存中的值并递增它。

++(*ptr)等同于(*ptr) += 1因此它会增加垃圾位置的值,现在您可以看到undefined behavior的效果,因此您无法获得最后一个递增的值加一,但因为未定义的行为而获得与最后一个相同的值。在我的编译器上,我得到了最后一个递增的值加一。

相关问题