C++ void指针与NULL指针

 指针有两个属性:指向变量/对象的地址和长度 但是指针只存储地址,长度则取决于指针的类型 
编译器根据指针的类型从指针指向的地址向后寻址 指针类型不同则寻址范围也不同,
例如: 
int*从指定地址向后寻找4字节作为变量的存储单元 
double*从指定地址向后寻找8字节作为变量的存储单元


void几乎只有“注释”和限制程序的作用

 

void真正发挥的作用在于:
(1) 对函数返回的限定;
(2) 对函数参数的限定

 

下面有使用void的规则:
规则一 如果函数没有返回值,那么应声明为void类型
规则二 如果函数无参数,那么应声明其参数为void
规则三 小心使用void指针

 按照ANSI(American National Standards Institute)标准,不能对void指针进行算法操作,即下列操作都是不合法的:
 ANSI标准之所以这样认定,是因为它坚持:进行算法操作的指针必须是确定知道其指向数据类型大小的。
 void * pvoid;
 pvoid++; //ANSI:错误
 pvoid += 1; //ANSI:错误
 int *pint;
 pint++; //ANSI:正确
 规则四 如果函数的参数可以是任意类型指针,那么应声明其参数为void *

典型的如内存操作函数memcpy和memset的函数原型分别为:
 void * memcpy(void *dest, const void *src, size_t len);
 void * memset ( void * buffer, int c, size_t num );
 任何类型的指针都可以传入memcpy和memset中,这也真实地体现了内存操作函数的意义,因为它操作的对象仅仅是一片内存,而不论这片内存是什么类型。如果memcpy和memset的参数类型不是void *,

规则五 void不能代表一个真实的变量
 void的出现只是为了一种抽象的需要,如果你正确地理解了面向对象中“抽象基类”的概念,也很容易理解void数据类型。正如不能给抽象基类定义一个实例,我们也不能定义一个void(让我们类比的称void为“抽象数据类型”)变量。

 

 

 下面解释一个概念,虽然在汉语中void pointer和null pointer都翻译为空指针,但是其是有区别的。

NULL Pointer: 
NULL pointer不指向任何实际物理内存地址
The concept of NULL pointer is different from the above concept of void pointer. 
NULL pointer is a type of pointer of any data type and generally takes a value as zero. 
This is, however, not mandatory. This denotes that NULL pointer does not point to any valid memory address.

For example:

int* exforsys; 
exforsys=0;

The above statement denotes exforsys as an integer pointer type that does not point to a valid memory address. This shows that exforsys has a NULL pointer value.


The difference between void pointers and NULL pointers: 
A Void pointer is a special type of pointer of void and denotes that it can point to any data type. 
NULL pointers can take any pointer type, but do not point to any valid reference or memory address.

NULL pointer和未初始化指针是有区别的:(下面是例子)
It is important to note that a NULL pointer is different from a pointer that is not initialized. 
For example, if a programmer uses the program below:

#include <iostream.h>
int *exforsys;
void main()
{
 *exforsys=100;
}

The output of the above program is 
NULL POINTER ASSIGNMENT
The above program will result in a runtime error. 
This means that the pointer variable exforsys is not assigned any valid address and, therefore, attempting to access the address 0 gives the above error message.


转自:http://blog.csdn.net/sosidami/article/details/5275349

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值