Chapter 7 Pointers(指针)
§ 1. Pointer Definition
A pointer is a variable that contains the address of a variable. 指针也是一个变量,它的值是另外一个变量的地址。
地址,就是内存里存储单元的编号。就像一条大街上的房子,每个房子都有门牌号。 int
For example, a char values is defined as follows: char aChar = ?G?;
p 145600 ? ?
//声明一个指针变量
char * p = &aChar; // p = 145600 p: 指针变量本身的名字; * 表示p是一个指针变量;
&:取地址运算符,返回变量地址; &aChar :代表变量aChar的地址。
= :把变量aChar的地址,赋给指针变量p;
此时,指针p里存储的,是字符变量aChar的地址,即指针p指向aChar。
char * :指针变量的类型,p是一个字符型指针。char代表指针指向的变量的类型。 int a = 10;
int * pa = &a; //pa是整型指针
float f = 1.0;
float * pf = &f; //pf是浮点型指针变量。
& assigns the address of aChar to the variable p, and p is said to ``point to'' aChar. The & operator only applies to objects in memory: variables and array elements.
The & operator
? & is the address operator 取地址运算符
? Use %p to print an address 在printf中,使用%p打印一个地址,打印指针变量的值。
For example:
?
Pointers : 4 byte Integers 指针变量是4个字节的整数
§ 2. Pointer Variables 指针变量
Pointer Variables is to define variables holding pointers. Pointer Variables:
– Contain an address 它的值就是个地址。
– Can have value changed 指针变量的值可以改变,存储一个新的地址,即指向另外的变量。
– “Point” to a specific type of data 它是有类型的。
– Many variables can point to the same value! 多个指针可以有同样的值,多个指针指向同一个变量。
§ 3. Accessing the Variables 通过指针,访问指针指向的变量。
? The Operator * is the dereference operator 解引用运算符,间接引用运算符。 ? “Dereferencing” often read as “contents of” * 解引用运算符的作用: char aChar = ?G?; char * p = &aChar;
*p:访问指针p指向的变量aChar。 *p放在等号右边,“读取”p指向的变量的值?G?;
*p放在等号左边,给指针p指向的变量aChar“写入”内容。
For example:
p = &a;
c = *p + 43; // c = a + 43;
? Add 43 to (*p) what p points to ? Assign this number to variable c
指针p,指向变量x;
*p代表指针p指向的变量,*p就是变量x。对*p的操作,就相当于对x的操作。 x =4;
x = x + 3; //x = 7; int y = x; //y = 7;
int z = *p; // 等价于int z = x; *p = 8; // 等价于 x = 8; *q + *p //等价于 x + x;
*&x :从右向左看,&x是x的地址,即指向x的指针,*&x等价于x。 *&x = *q + *p 等价于x = x + x。
printf(“x = %d ”, x); printf(“x = %d ”, *p); printf(“x = %d ”, *q);
§ 4. Declaring Pointer Variables 声明一个指针变量
Examples:
char *p; int *q; float *r;
long double *s; long int *t;
§ 5. Uninitialized Pointers 未初始化的指针
As with all variables in C:
If you don?t initialize you get whatever junk is found at that time !!! 如果变量没有初始化,它里面的内容是垃圾信息。
相关推荐: