.
Variables that can store addresses are called pointers.
指针一般指向的是这个数据的第一个字节,所以你还需要知道指针所指的类型,这样你才知道数据一共占用多少字节,例如char类型占用一个字节,long占用4个字节。
类型名为void表示没有指定类型,所以void*类型的指针可以包含任意类型的数据项地址。类型void*常常用做参数类型,或以独立于类型的方式处理数据的函数的返回值类型。任意类型的指针都可以传送为void*类型的值,在使用它时,再将其转换为合适的类型。例如, int类型变量的地址可以存储在void*类型的指针变量中。要访问存储在void*指针所指地址中的整数值,必须先把指针转化为int *类型。
申明指针
1 | int *pnumber; |
指针如果没有初始化比类型没有初始化更危险,因为有可能会覆盖该内存。NULL被定义在stddef.h,stdlib.h,stdio.h,string.h,time.h,wchar.handlocale.h
给指针对象所指的变量赋值
1 | int number = 99; |
通过指针访问值
1 | int number = 15; |
示例
1 | int number = 0; |
1 | number's address: 0x7ffeefbff5c4 //打印number的地址 |
pnumber 访问是pnumber自己的参数,也就是pnumber所指的参数的地址。*pnumber访问pnumber所指地址参数的值&pnumber访问pnumber自己的地址值。
The effect of the * operator is to access the data contained in the address stored at pnumber.
The *operator is called the indirection operator or sometimes the dereferencing operator.
The cast to void* is to prevent a possible warning from the compiler.
使用指针
1 | long num1 = 0L; |
表达式
++*pnum递增了pnum指向的值。但如果要使用后置的形式,必须写成(*pnum)++。括号很重要,它指定要递增的是数值,而不是地址。这是因为运算符++和一元运算符&的优先级相同,且都是从左到右计算的。
测试NULL指针
1 | int *pvalue = NULL; |
NULL在C语言中是一个特俗的常量,它相当于数字0的指针。NULL常量定义为((void*))0。给指针赋予0时,就等于它设为NULL。
指向常量的指针
1 | long value = 99999L; |
常量指针
1 | int count = 43; |
1 | const long *const kcount = &value: //定义的kcount指针既不能修改kcount指向的值,也不能修改指向的内存地址。 |
指针的命名
因为在C中很那区分哪个是指针,哪个是变量。那么如果是指针的话,可以在前面加p作为针名的第一个字母。