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

3

代码:

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

我希望输出结果如下: 5 junk 5 7 很抱歉,我的指针和运算符优先级概念非常模糊。无法理解这个简单的输出。


3
@fotanus,那会有什么区别呢? - JJJ
@fotanus 我非常确定那不是它的工作方式。 - JJJ
1
我有一个故意不理解这些优先规则的观点,我只是以一种新手程序员可以理解的方式编写代码,因为他们可能有一天需要维护我的代码。如果你试图维护看起来像这样的代码,请首先理解其意图,然后重新编写代码,使测试仍然通过。你有测试吗? - jhabbott
@Juhana,抱歉,我的意思是+1,而不是+= 1 :p - fotanus
@fotanus 如果OP正在练习指针和递增的组合,那该怎么办? - Dennis Meng
显示剩余2条评论
4个回答

6
  1. 显然是5,只需解引用指针
  2. 仍然是5,因为后缀操作符返回先递增的指针
  3. 3和4是垃圾值,因为指针不再指向已分配的内存

如果您希望第二项像您期望的那样打印垃圾值,可以使用前缀++


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.

3
为什么要使用%注释而不是//呢? - ravron
@Riley,我的错误很傻。我正在使用MATLAB工作。我已经纠正了它。谢谢你提醒我。 - radarhead
一般来说,我不在这里做它,因为这是答案,所以我认为让它可见 :) - Grijesh Chauhan

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

*ptr 只是给出了位置上的值,也就是a的值。

*(ptr++) 等同于 (*ptr),然后 (ptr += 1),因为它是后置递增运算符,所以首先它会给出printf使用的值,然后递增指针,这样它现在指向垃圾内存。

(*ptr)++ 等同于 (*ptr),然后 (*ptr += 1),因此它取得了垃圾内存中的值并将其递增。

++(*ptr) 等同于 (*ptr) += 1,所以它递增了垃圾位置上的值,现在你可以看到未定义行为的影响,因此您不能获得最后递增的值加一,但由于未定义行为而得到了与上一个相同的值。在我的编译器上,我得到了最后递增的值加一。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接