转自:http://www.cnblogs.com/youxin/archive/2012/03/27/2420023.html
先看下面一段代码输出什么:
#include<stdo.h>
int main()
{
int *p=NULL;
printf("%s",p);
}
输出<null> ,单步调试可以看出执行int *p=NULL,p的值为0x00000000,可以看出,NULL在实际底层调用中就是0,
在C语言中,
NULL和0的值都是一样的,但是为了目的和用途及容易识别的原因,NULL用于指针和对象,0用于数值
对于字符串的结尾,使用'\0',它的值也是0,但是让人一看就知道这是字符串的结尾,不是指针,也不是普通的数值
在不同的系统中,
NULL并非总是和0等同,NULL仅仅代表空值,也就是指向一个不被使用的地址,在大多数系统中,都将0作为不被使用的地址,所以就有了类似这样的定义
#define NULL 0
但并非总是如此,也有些系统不将0地址作为NULL,而是用其他的地址,所以说,千万别将NULL和0等价起来,特别是在一些跨平台的代码中,这更是将给你带来灾难。
看下面解释:
问 0 '0' '\0' "\0"
To me, when doing C/C++:
0 would digit zero, that is, a numerical value.
'0' could be the character capital oh or the character zero. For example: char word[10] = "Oxford"; char number[10] = "01234";
Depending on typeface used 'O' may look exactly like '0' making it difficult to tell them apart out of context.
'\0' is the null character used to terminate strings in C/C++.
"\0" is an empty string.
NULL在stdio.h中定义:
#if !defined(NULL) && defined(__NEEDS_NULL) #ifdef __cplusplus #define NULL 0 #else #define NULL ((void *)0) #endif #endif
在c++定义为0,在c中定义为(void *)0;为什么,参考:http://stackoverflow.com/questions/7016861/null-pointer-in-c-and-c

