检查'C'中的NULL字符时出现奇怪的行为

liv*_*hak 0 c null pointers

为了澄清一点,我写了两个小测试程序,如下所示.

#include <stdio.h>                                                                                                                                                                       

int main(int argc, char *argv[])
{
    char *p = "ab";
    p++;
    p++;

    if (*p)
        printf("p is not NULL \n");
    else
        printf("ps is NULL \n");

    return 0;

 }
Run Code Online (Sandbox Code Playgroud)

上面的程序初始化p字符串文字的char指针ab.我将指针递增两次,然后if循环检查是否p指向非NULL字符.这样可以正常工作并提供以下输出.

ps is NULL 
Run Code Online (Sandbox Code Playgroud)
#include <stdio.h>


int main(int argc, char *argv[])
{
    char *p = '\0';                                                                                                                                                                      

    if (*p)
        printf("p is not NULL \n");
    else
        printf("ps is NULL \n");

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

上面的程序将char指针初始化p为NULL字符\0.如果我编译并运行程序,我会得到分段错误.有人解释一下吗?

两种情况的唯一区别是NULL字符位于位置0和位置.2否则程序看起来与我相同.

Kei*_*son 7

理解空指针(NULL)和空*字符('\0')之间的区别很重要.

char *p = "ab";
p++;
p++;
Run Code Online (Sandbox Code Playgroud)

这正确地将指针设置为指向p字符串末尾的空字符"ab".

char *p = '\0';
Run Code Online (Sandbox Code Playgroud)

这设置p为空指针.使用'\0'空指针常量是不好的样式,但是合法的(任何具有零值的常量整数表达式都是有效的空指针常量).以上相当于更清晰:

char *p = NULL;
Run Code Online (Sandbox Code Playgroud)

任何取消引用的尝试p都有未定义的行为,并且可能会导致程序崩溃.

两种情况的唯一区别是NULL角色位于0位和2位.

如果你想NULL在位置0 有一个空字符(不是字符),你可以写:

char *p = "\0";
Run Code Online (Sandbox Code Playgroud)

或者,几乎相当于:

char *p = "";
Run Code Online (Sandbox Code Playgroud)

空字符串仅包含终止'\0'空字符.

  • @localhost:空字符*通常被称为"NUL".我相信它是ASCII中的官方(?)缩写.Unicode将其称为"NULL",但我在讨论C时尽量避免使用该名称. (2认同)