-5

我有一个关于 C 中这个简单程序的问题,用于练习指针和数组。

代码:

#include <stdio.h>

fun(int *p, int *v) {
    *p++;
    *(v+2) = p[3];
    *v++ = p[0];
    v[0] = *(p+4);
}

int main() {

    int v[] = {90, 89, 8, 78, 60, 120};
    int k[] = {0, 0, 0, 0, 0, 0};
    int *ptr = k;

    fun(v, ptr);
    for (ptr = k; ptr < k + 6; ptr++)
        printf("%d\n", *ptr);
}

所以我的问题是它为什么会打印89 120 60 0 0 0

4

1 回答 1

2

It's useful to draw out (even by hand on paper!) what's going on with pointers and arrays. For the following function:

void fun(int *p, int *v) {
    *p++;
    *(v+2) = p[3];
    *v++ = p[0];
    v[0] = *(p+4);
}

You have passed these arrays:

[90] [89] [8] [78] [60] [120]
 |
 p

[0]  [0]  [0] [0]  [0]  [0]
 |
 v

What happens in fun?

*p++

This could be read one of two ways: Dereference p and (post) increment that value, or post-increment p and dereference the old value of p. Which is it? Our handy table of operator precedence says ++ comes before *, so it's the second one. Notice that we deference a pointer, but don't do anything the value. That means we could have written p++ and gotten the same result.

After the increment, our pointer has changed:

[90] [89] [8] [78] [60] [120]
      |
      p

The next line uses both p and v:

    *(v+2) = p[3];

You can read this as "assign the 3rd value to the right of p to the 2nd spot to the right of v." The third spot to the right of p has 60, and it goes here:

[0]  [0]  [60] [0]  [0]  [0]
 |
 v

Next up:

*v++ = p[0];

From before, we know that *v++ means (post) increment v. The difference between ++v (pre-increment) and v++ (post-increment) is what value gets returned - in this case, we'll modify v but use its old value, assiging what p is pointing at. Notice that v has been incremented:

[89]  [0]  [60] [0]  [0]  [0]
       |
       v

And finally:

v[0] = *(p+4);

This can be read as "assign th e 4th value to the right of p to the 0th spot to the right of v." The forth spot to the right of p has 120, and it goes here:

[89]  [120]  [60] [0]  [0]  [0]
       |
       v

So at the end of the function, this is what our pointers and memory look like:

[90] [89] [8] [78] [60] [120]
 |    |
 |    p
main-v

[89]  [120]  [60] [0]  [0]  [0]
 |     |
 |     v
main-k
main-ptr
于 2013-06-14T17:31:28.123 回答