最近更新:26th 4月, 2015
大家在学习指针的时候可能会有很多的东西让大家迷惑那么我用一下几个小小的实验程序来给大家解答疑惑:
首先从定义上讲指针是一种保存在变量地址的变量。
一元运算符*是间接寻址或间接引用的运算符
一元运算符&用于取一个对象的地址,只能应用于内存中的对象
也就是说*(间接寻址得到的是一个在内存中存储的具体的值)
对于指针的实验
实验一
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
[root@localhost~]# vim zhizhenshiyan1.c
#include
main(void)
{
intx=1;
int*ip;
ip=&x;
printf("十进制显示d ip=%d\n",ip);
printf("十进制显示d *ip=%d\n",*ip);
printf("二进制显示x ip=%x\n",ip);
printf("二进制显示x *ip=%x\n",*ip);
}
编译后的结果为
1
2
3
4
5
6
7
8
9
[root@localhost~]# ./a.out
十进制显示dip=928094692
十进制显示d*ip=1
二进制显示xip=375199e4
二进制显示x*ip=1
指针是一个保存变量地址的变量,在实验一中,
ip=&x;
ip指向x将x的地址给ip
我们将x的地址赋值给变量ip
我刚刚学习这个的时候在这个地方理解的不是很深刻于是就有了实验一
从实验一中我们可以知道直接寻址和简介寻址的区别,我分别用十进制和二进制打印了直接寻址和简介寻址的值,
直接寻址则是打印的x在内存中的地址信息,直接寻址得到的数据是一个地址
而间接寻址则是在直接寻址的基础上建立起来的,简介寻址的值为所对应的地址中存储的对象。
实验二
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include
main(void)
{
intx=1,y=2;
int*ip;
printf("int x=1 , y=2;\nint *ip\n");
ip=&x;
printf("ip=&x=%d\n",ip);
y=*ip;
printf("y=*ip=%d\n",y);
*ip=0;
printf("*ip=0 x=%d\n",x);
printf("&x=%d",&x);
}
———————————————-
1
2
3
4
5
6
7
8
9
10
11
12
13
[root@localhost~]# ./a.out
intx=1,y=2;
int*ip
ip=&x=1226821388
y=*ip=1
*ip=0x=0
&x=1226821388
—————————————-
由实验二我们可以得到以下的信息
首先指针是一个变量,可以进行改变。
1
2
3
4
5
6
7
intx=1,y=2;
*ip=0;
printf("*ip=0 x=%d\n",x);
printf("&x=%d",&x);
这几行代码告诉我们间接寻址赋值则改变的是地址中的对象。通过前后两次对直接寻址&x的输出可以得知
====================
实验三
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include
main(void)
{
intz;
intx=1,y=2;
chara='!',b='#';
int*ip,*ab;
char*c,*d;
ip=&x;
ab=&y;
printf("int z\nint x=1,y=2\nint *ip,*ab;\n*ip=&x *ab=&y\n");
*ip=*ip+10;
printf("*ip=*ip+10=%d\n",*ip);
z=*ip+*ab;
printf("z=*ip+*ab=%d\n",z);
}
编译后结果
1
2
3
4
5
6
7
8
9
10
11
12
13
[root@localhost~]# ./a.out
intz
intx=1,y=2
int*ip,*ab;
*ip=&x*ab=&y
*ip=*ip+10=11
z=*ip+*ab=13
间接寻址得到的是值,他们的运算为值的运算/
================
实验四
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include
main(void)
{
charx=1,y=2;
char*ip;
ip=&x;
*ip=123;
printf("%c",*ip);
}
运行后的结果
1
2
3
[root@localhost~]# ./a.out
{
在 asc 码中123表示的是符号”{“
这个实验其实很简单的告诉了我们直接引用和间接引用的各种关系,直接引用则是引用的存放值的地址的值(地址的编码)在asc码中123表示的是符号{所以在输出*ip直接引用123号存储位置的时候表示的是符号”{“.
=====================
ps:在32位的系统中指针的值可以用 int 值表示甚至可以相互进行一元运算,尤其是指的 asc 码