使用指向字符的常量指针时使用引用操作符与C中的普通初始化相比


#include <stdio.h>
int main()
{
    char *p = 'c'; 
    char *q;
    char a = 'd' ;
    q = &a;
    printf("%cn",*q);
    printf("%cn",p);
    printf("%cn",q);
    printf("%dn",q);
    printf("%cn",*p);
    return 0;
}
输出:

d
c

881895631段故障(core dump)

第一个、第三个和第四个printfs输出和预期的一样,但是有人能解释一下为什么字符指针不需要解引用(就像第二个printf语句一样)吗?没有使用解引用操作符,它给出了输出。但是当我尝试使用指针p的引用运算符时,它给出了一个分割错误。请解释。

您正在初始化一个带有int值的指针,即'c'。你的编译器应该对此产生一个警告。

指针实际上包含了值67,这是一个你不能访问的地址。因此,如果你解引用这个指针,你尝试读取存储在地址67的字符,这在大多数情况下会导致程序崩溃,因为这个地址从来没有分配给你的程序。

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

最新更新