简体   繁体   English

以下程序输出为什么是5,而不是4? 谁能解释?

[英]How come the following program output is 5, not 4? Could anyone explain?

I came upon a program which outputs 5. I don't know how. 我遇到了一个输出5的程序。我不知道如何。 Please explain. 请解释。

int main(void) {
        int t[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }, *p = t;
        p += 2;
        p += p[-1];
        printf("\n%d",*p);
        return 0;
    }

I expect the output to be 4. the pointer moves from t[0] to t[2] here(p+=2;). 我希望输出为4。在这里,指针从t [0]移至t [2](p + = 2;)。 In the next statement p+= p[-1], I believe pointer moves to t[1] whose value is 2 first and so increased by 2. So I expected output to be 4. but the actual output is 5. Anyone, please explain? 在下一条语句p + = p [-1]中,我相信指针会先移至t [1],其值首先为2,然后增加2。因此我希望输出为4,但实际输出为5。说明?

p = t; // p = &t[0]
p += 2; // p = &t[2]
p += p[-1]; // p += 2; // p = &t[4]

At first, the pointer p points to the beginning of the array t . 首先,指针p指向数组t的开头。 So it should be something like 所以应该像

p--
  |
  v
------------------------------------------
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 |
------------------------------------------

Now by 现在通过

p += 2

p is increment according to pointer arithmetic. p是根据指针算法得出的增量。 So that p is now pointing to 3 . 因此, p现在指向3

p----------
          |
          v
------------------------------------------
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 |
------------------------------------------

p[-1] is same as *(p-1) . p[-1]*(p-1) ie, the value at the address p-1 . 即,地址p-1处的值。 This value is 2 . 该值是2

      ------ p[-1] or *(p-1)
      |
      |
------|-----------------------------------
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 |
------------------------------------------

After adding 2 to the current value of p , p would now be pointing to 5 . 在将p的当前值加2之后, p现在将指向5

p------------------
                  |
                  v
------------------------------------------
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 |
------------------------------------------

So, when you print the value of *p , 5 is output. 因此,当您打印*p的值时,将输出5

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM