在使用指向字符的常量指针与 C 中的正常初始化时使用引用运算符

Using reference operator when using a constant pointer to a character vs normal initialization in C

#include <stdio.h>

int main()
{
    char *p = 'c'; 
    char *q;
    char a = 'd' ;
    q = &a;
    printf("%c\n",*q);
    printf("%c\n",p);
    printf("%c\n",q);
    printf("%d\n",q);
    printf("%c\n",*p);
    return 0;
}

输出:

d
c

881895631 Segmentation fault (core dumped)

第一个、第三个和第四个 printfs 输出符合预期,但有人可以解释为什么不需要取消引用字符指针(如第二个 printf 语句)。在不使用取消引用运算符的情况下,它给出了输出。但是当我尝试使用指向指针 p 的引用运算符时,它给出了分段错误。请解释。

您正在初始化一个具有 int 值的指针,即 'c'。您的编译器应该为此发出警告。

所以你的指针实际上包含值67,这是一个你肯定无法访问的地址。因此,如果您取消引用该指针,请尝试读取存储在地址 67 的字符,这在大多数情况下会使您的程序崩溃,因为该地址从未分配给您的程序。

printf("%c\n",*q);  // ok
printf("%c\n",p);   // undefined behaviour: %c is for printing chars
                    // but as p contains 67 (ASCII value of 'C') ends up printing c
printf("%c\n",q);   // undefined behaviour: %c is for printing chars
printf("%d\n",q);   // undefined behaviour: %d is for printing chars and not pointers
printf("%c\n",*p);  // undefined hahaviour (mostly crashes), see explanation above