使用指针打印变量值时出现意外输出

时间:2015-09-13 08:12:28

标签: c pointers

#include <stdio.h>
int main()
{
    int i = 5;
    int* u = &i;
    printf("%d\n", *(u + 0));
    for(i = 0; i < 10; i++)
        printf("%d\n", *u);
}

输出是:

5
0
1
2
3
4
5
6
7
8
9

但我认为应该打印5 11次。

1 个答案:

答案 0 :(得分:2)

由于你包含变量i的地址,对i的任何更改都会反映在*u的值中。所以通过代码:

#include <stdio.h>
int main()
{
    int i = 5;
    int* u = &i;    //u contains the address of i so change in i changes *u
    printf("%d\n", *(u + 0));    //prints the value of i as *u is the value i that is 5
    for(i = 0; i < 10; i++)    //the value of i changes so does *u.Therefore *u is incremented from 0 to 9 1 at a time.
    printf("%d\n", *u);     //prints the value of *u whch is effectively i
 }