代码:
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 很抱歉,我的指针和运算符优先级概念非常模糊。无法理解这个简单的输出。
代码:
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 很抱歉,我的指针和运算符优先级概念非常模糊。无法理解这个简单的输出。
如果您希望第二项像您期望的那样打印垃圾值,可以使用前缀++
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.
%
注释而不是//
呢? - ravronint 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
*ptr
只是给出了位置上的值,也就是a
的值。
*(ptr++)
等同于 (*ptr)
,然后 (ptr += 1)
,因为它是后置递增运算符,所以首先它会给出printf使用的值,然后递增指针,这样它现在指向垃圾内存。
(*ptr)++
等同于 (*ptr)
,然后 (*ptr += 1)
,因此它取得了垃圾内存中的值并将其递增。
++(*ptr)
等同于 (*ptr) += 1
,所以它递增了垃圾位置上的值,现在你可以看到未定义行为
的影响,因此您不能获得最后递增的值加一,但由于未定义行为而得到了与上一个相同的值。在我的编译器上,我得到了最后递增的值加一。