#include <stdio.h>
void main ()
{
int* p = NULL;
printf("%d", *p);
}
它打印:
Exception thrown: read access violation.
p was nullptr.
最佳答案
NULL 指针不能被取消引用。
这样做会调用 undefined behavior ,在这种情况下表现为您的程序崩溃。
这记录在 C standard 的第 6.5.3.2p4 节中:
4 The unary
*
operator denotes indirection. If the operand points to a function, the result is a function designator; if it points to an object, the result is an lvalue designating the object. If the operand has type "pointer to type", the result has type "type". If an invalid value has been assigned to the pointer, the behavior of the unary * operator is undefined. 102)102) Thus,
&*E
is equivalent toE
(even if E is a null pointer), and&(E1[E2])
to((E1)+(E2))
. It is always true that ifE
is a function designator or an lvalue that is a valid operand of the unary&
operator,*&E
is a function designator or an lvalue equal toE
. If*P
is an lvalue andT
is the name of an object pointer type,*(T)P
is an lvalue that has a type compatible with that to whichT
points.Among the invalid values for dereferencing a pointer by the unary
*
operator are a null pointer, an address inappropriately aligned for the type of object pointed to, and the address of an object after the end of its lifetime.
如果你想打印指针本身,将它传递给 printf
而不取消引用它并使用 %p
格式说明符:
printf("%p\n", (void *)p);
关于c - 为什么在尝试打印空指针时出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55123976/