晕头转向的指针

指针

 1 int main(void)
2 {
3 int i = 0;
4 int x = 1;
5 int y = 2;
6
7 printf("&i %p |&x %p |&y %p \n",&i,&x,&y);
8
9 int *pi = &i;
10 printf("pi %p |*pi %d |&pi %p \n",pi,*pi,&pi);
11
12 pi = &x;
13 printf("pi %p |*pi %d |&pi %p \n",pi,*pi,&pi);
14
15 *pi = y;
16 printf("i %d |x %d |y %d \n",i,x,y);
17 printf("pi %p |*pi %d |&pi %p \n",pi,*pi,&pi);
18
19 x = 1;
20 printf("i %d |x %d |y %d \n",i,x,y);
21 printf("pi %p |*pi %d |&pi %p \n",pi,*pi,&pi);
22
23 return 0;
24 }

输出

&i 0x7fffc34c716c |&x 0x7fffc34c7168 |&y 0x7fffc34c7164
pi 0x7fffc34c716c |*pi 0 |&pi 0x7fffc34c7158
pi 0x7fffc34c7168 |*pi 1 |&pi 0x7fffc34c7158
i 0 |x 2 |y 2
pi 0x7fffc34c7168 |*pi 2 |&pi 0x7fffc34c7158
i 0 |x 1 |y 2
pi 0x7fffc34c7168 |*pi 1 |&pi 0x7fffc34c7158

 

const 和 指针的缠绵

 1 int main(void)
2 {
3 int i = 0;
4 int x = 1;
5 int y = 2;
6
7 printf("&i %p |&x %p |&y %p \n",&i,&x,&y);
8
9 int const *pi = &i;
10 printf("pi %p |*pi %d |&pi %p \n",pi,*pi,&pi);
11
12 pi = &x;
13 printf("pi %p |*pi %d |&pi %p \n",pi,*pi,&pi);
14
15 // *pi = y;
16 // printf("i %d |x %d |y %d \n",i,x,y);
17 // printf("pi %p |*pi %d |&pi %p \n",pi,*pi,&pi);
18
19 x = 99;
20 printf("i %d |x %d |y %d \n",i,x,y);
21 printf("pi %p |*pi %d |&pi %p \n",pi,*pi,&pi);
22
23 return 0;
24 }

输出

&i 0x7fff18dd9aac |&x 0x7fff18dd9aa8 |&y 0x7fff18dd9aa4
pi 0x7fff18dd9aac |*pi 0 |&pi 0x7fff18dd9a98
pi 0x7fff18dd9aa8 |*pi 1 |&pi 0x7fff18dd9a98
i 0 |x 99 |y 2
pi 0x7fff18dd9aa8 |*pi 99 |&pi 0x7fff18dd9a98

  • 经过const修饰的*pi是只读的
 1 int main(void)
2 {
3 int i = 0;
4 int x = 1;
5 int y = 2;
6
7 printf("&i %p |&x %p |&y %p \n",&i,&x,&y);
8
9 int *const pi = &i;
10 printf("pi %p |*pi %d |&pi %p \n",pi,*pi,&pi);
11
12 // pi = &x;
13 // printf("pi %p |*pi %d |&pi %p \n",pi,*pi,&pi);
14
15 *pi = y;
16 printf("i %d |x %d |y %d \n",i,x,y);
17 printf("pi %p |*pi %d |&pi %p \n",pi,*pi,&pi);
18
19 i = 99;
20 printf("i %d |x %d |y %d \n",i,x,y);
21 printf("pi %p |*pi %d |&pi %p \n",pi,*pi,&pi);
22
23 return 0;
24 }

输出

&i 0x7fffd8c6d51c |&x 0x7fffd8c6d518 |&y 0x7fffd8c6d514 

pi 0x7fffd8c6d51c |*pi 0 |&pi 0x7fffd8c6d508
i 2 |x 1 |y 2
pi 0x7fffd8c6d51c |*pi 2 |&pi 0x7fffd8c6d508
i 99 |x 1 |y 2
pi 0x7fffd8c6d51c |*pi 99 |&pi 0x7fffd8c6d508

  • 经过const修饰的pi是只读的
 1 int main(void)
2 {
3 int i = 0;
4 int x = 1;
5 int y = 2;
6
7 printf("&i %p |&x %p |&y %p \n",&i,&x,&y);
8
9 const int *const pi = &i;
10 printf("pi %p |*pi %d |&pi %p \n",pi,*pi,&pi);
11
12 //pi = &x;
13 //printf("pi %p |*pi %d |&pi %p \n",pi,*pi,&pi);
14
15 //*pi = y;
16 //printf("i %d |x %d |y %d \n",i,x,y);
17 //printf("pi %p |*pi %d |&pi %p \n",pi,*pi,&pi);
18
19 i = 99;
20 printf("i %d |x %d |y %d \n",i,x,y);
21 printf("pi %p |*pi %d |&pi %p \n",pi,*pi,&pi);
22
23 return 0;
24 }

输出

&i 0x7ffff3726f0c |&x 0x7ffff3726f08 |&y 0x7ffff3726f04
pi 0x7ffff3726f0c |*pi 0 |&pi 0x7ffff3726ef8
i 99 |x 1 |y 2
pi 0x7ffff3726f0c |*pi 99 |&pi 0x7ffff3726ef8

  • 这下好了*pi和pi都是只读了

posted on 2011-11-24 11:33  I'm legend  阅读(337)  评论(0编辑  收藏  举报