#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
关于c - 使用指向字符的常量指针时使用引用运算符与 C 中的正常初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31936773/