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 抱歉,我的指针和运算符优先级概念非常暗淡。无法理解这个简单的输出。

4

4 回答 4

6
  1. 第一个明显是5,只是解引用一个指针
  2. 仍然是五个,因为后缀运算符返回指针预增量
  3. 3 和 4 是垃圾,因为指针不再指向已分配的内存

如果您希望第二个像您预期的那样运行并打印垃圾,您可以使用前缀++代替

于 2013-08-08T18:33:18.667 回答
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.
于 2013-08-08T18:36:29.937 回答
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
于 2013-08-08T18:44:25.220 回答
3

*ptr只是给出该位置的值,该值只不过是 的值a

*(ptr++)等价于(*ptr)and then(ptr += 1)因为post increment ,所以首先它给出 printf 使用的值,然后增加指针,所以现在它指向 junk memory 。

(*ptr)++等价于(*ptr)and (*ptr += 1),所以它取垃圾内存中的值并增加它。

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

于 2013-08-08T18:44:25.630 回答