Null pointer in C++

前端 未结 8 462
悲&欢浪女
悲&欢浪女 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:29

    It means that an integral constant expression with value zero has a special meaning in C++; it is called a null pointer constant. when you use such an expression to initialize a pointer with, or to assign to a pointer, the implementation ensures that the pointer contains the appropriately typed null pointer value. This is guaranteed to be a different value to any pointer pointing at a genuine object. It may or may not have a representation that is "zero".

    ISO/IEC 14882:2011 4.10 [conv.ptr] / 1:

    A null pointer constant is an integral constant expression (5.19) prvalue of integer type that evaluates to zero or a prvalue of type std::nullptr_t. A null pointer constant can be converted to a pointer type; the result is the null pointer value of that type and is distinguishable from every other value of object pointer or function pointer type.

    0 讨论(0)
  • 2021-01-14 20:29

    It's a special value, which by the standard is guaranteed to never be equal to a pointer that is pointing to an object or a function. The address-of operator & will never yield the null pointer, nor will any successful dynamic memory allocations. You should not think of it as address 0, but rather as special value that indicates that the pointer is pointing nowhere. There is a macro NULL for this purpose, and the new idiom is nullptr.

    0 讨论(0)
  • 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?

    0 讨论(0)
  • 2021-01-14 20:32

    The value of the pointer is just 0. It doesn't necessarily mean it points to address 0x0. The NULL macro, is just a 0 constant.

    0 讨论(0)
  • 2021-01-14 20:32

    the pointer points to address 0. On most platforms that is very special, but you should use NULL, because it is not always 0 (but very often).

    0 讨论(0)
  • 2021-01-14 20:36

    It means that it's not pointing to anything.

    0 讨论(0)
提交回复
热议问题