你搞清楚「NULL」、「0」、「'0'」、「"0"」「\0」了吗?

嵌入式Linux

共 302字,需浏览 1分钟

 · 2020-11-28


我们先讨论NULL,平时使用指针的时候,会经常遇见这个家伙,这个家伙的值是是这样定义的

#define NULL 0
或者
#define NULL (void *)0

我们看一下下面这段代码

#include 

int main () {
    size_t ii;
    int *ptr = NULL;
    unsigned long *null_value = (unsigned long *)&ptr;
    if (NULL == 0) {
        printf ("NULL == 0\n"); }
    printf ("NULL = 0x");
    for (ii = 0; ii < sizeof (ptr); ii++) {
        printf ("%02X", null_value[ii]); }
    printf ("\n");
    return 0;
}

程序输出

NULL == 0
NULL = 0x000061FE08000400B1138000

--------------------------------
Process exited after 0.02921 seconds with return value 0
请按任意键继续. . .

我们用 &ptr 获取 ptr的地址,然后用 unsigned long * 把这个地址转换成 unsigned long *类型,之后再用 * 钥匙来打开这个地址,获取这个地址的值。只不过这里不是用 *获取,用的是数组偏移。

我们修改下代码

#include 

int main () {
    size_t ii;
    int *ptr = NULL;
    unsigned long *null_value = (unsigned long *)&ptr;
    if (NULL == 0) {
        printf ("NULL == 0\n"); }
    printf ("NULL = 0x");
    for (ii = 0; ii < sizeof (ptr); ii++) {
        printf ("%02X", null_value[ii]); }
    printf ("\n");
    printf("0x%p 0x%p\n",ptr,&ptr);
    return 0;
}

程序输出

NULL == 0
NULL = 0x000061FE08000400A7138000
0x0000000000000000 0x000000000061FE08

--------------------------------
Process exited after 0.03177 seconds with return value 0
请按任意键继续. . .

这样看之后,就觉得没有那么拗口了吧。

我们再讨论下 「'0'」

字符 0 和其他都不能混为一谈,它是一个字符,字符对应的是ascii 码

#include 

int main () {
 char c = '0'
 printf("'%c' 0x%x %d\n",c,c,c); 
    return 0;
}

程序输出

'0' 0x30 48

--------------------------------
Process exited after 0.02841 seconds with return value 0
请按任意键继续. . .

「"0"」是一个字符串,字符串跟字符的不同是,字符串在最后面有一个字符结束标识 nul

测试程序

#include 
#include 
int main () {
 char * str = "0"
 int len = strlen(str);
 printf("%d\n",len); 
 for(int i = 0;i< len +1;i++)
  printf("[0x%x]",str[i]);
    return 0;
}

程序输出

1
[0x30][0x0]
--------------------------------
Process exited after 0.02936 seconds with return value 0
请按任意键继续. . .

「\0」这个就有点意思了,这个其实也就是数值 0

测试程序

#include 
#include 
int main () {
 char c = '\0';
 printf("'%c' 0x%x %d\n",c,c,c); 
    return 0;
}

程序输出

' ' 0x0 0

--------------------------------
Process exited after 0.03893 seconds with return value 0
请按任意键继续. . .

好了,就这些,看了这些之后,就再也不用担心如果一个字符串里面有 0 字符不知道怎么做算法比较了吧。


推荐阅读:专辑|Linux文章汇总专辑|程序人生专辑|C语言


嵌入式Linux微信扫描二维码,关注我的公众号 


浏览 5
点赞
评论
收藏
分享

手机扫一扫分享

举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

举报