简体   繁体   中英

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. 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;). 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 = 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 . 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. So that p is now pointing to 3 .

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

p[-1] is same as *(p-1) . ie, the value at the address p-1 . This value is 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------------------
                  |
                  v
------------------------------------------
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 |
------------------------------------------

So, when you print the value of *p , 5 is output.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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