Null pointer in C++

前端 未结 8 625
悲&欢浪女
悲&欢浪女 2021-01-14 20:02

When in C++ I declare a null pointer to be int* p=0, does that mean the zero is some special constant of integer pointer type, or does it mean that p

8条回答
  •  佛祖请我去吃肉
    2021-01-14 20:30

    In your example 'p' is the address of an int. By setting p to 0 you're saying there is an int at address 0. The convention is that 0 is the "not a valid address address", but its just a convention.

    In pratice address 0 is generally "unmapped" (that is there is no memory backing that address), so you will get a fault at that address. That's not true in some embedded systems, though.

    You could just as well pick any random address (e.g. 0xffff7777 or any other value) as the "null" address, but you would be bucking convention and confusing a lot of folks that read your code. Zero is generally used because most languages have support for testing is-zero is-not-zero efficiently.

    See this related question: Why is address zero used for the null pointer?

提交回复
热议问题