C++ Null Pointers
When declaring a variable, if there is no exact address to assign, it is good programming practice to assign a NULL value to the pointer variable. A pointer assigned a NULL value is called anullpointer.
A NULL pointer is a constant defined in the standard library with a value of zero. See the program below:
Example
#include
using
namespace
std
;
int
main
(
)
{
int
ptr
=
NULL
;
cout
<<
"The value of ptr is "
<<
ptr
;
return
0
;
}
When the code above is compiled and executed, it produces the following result:
ptr 的值是 0
On most operating systems, programs are not allowed to access memory at address 0, because that memory is reserved by the operating system. However, memory address 0 has special significance: it indicates that the pointer does not point to an accessible memory location. By convention, if a pointer holds a null value (zero), it is assumed to point to nothing.
To check for a null pointer, you can use an if statement, as shown below:
if(ptr) /* 如果 ptr 非空,则完成 */
if(!ptr) /* 如果 ptr 为空,则完成 */
Therefore, if all unused pointers are assigned a null value and accidental use of null pointers is avoided, misuse of uninitialized pointers can be prevented. Often, uninitialized variables hold garbage values, making programs difficult to debug.
C++ Pointers