代码:
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.
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
*ptr
只是给出该位置的值,该值只不过是 的值a
。
*(ptr++)
等价于(*ptr)
and then(ptr += 1)
因为post increment ,所以首先它给出 printf 使用的值,然后增加指针,所以现在它指向 junk memory 。
(*ptr)++
等价于(*ptr)
and (*ptr += 1)
,所以它取垃圾内存中的值并增加它。
++(*ptr)
等效于(*ptr) += 1
so 它增加垃圾位置的值,现在您可以看到效果, undefined behavior
因此您不会获得最后一个增加的值加一,而是由于未定义的行为而获得与最后一个相同的值。在我的编译器上,我得到了最后一个递增的值加一。