轉自: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