C ++ Null Pointer
At the time of variable declarations, if not the exact address can be assigned, assign a NULL value for the pointer variable is a good programming practice. Fu NULL pointer value is called anull pointer.
A NULL pointer is defined in the standard library zero constants. Consider the following program:
#include <iostream> using namespace std; int main () { int *ptr = NULL; cout << "ptr 的值是 " << ptr ; return 0; }
When the above code is compiled and executed, it produces the following results:
ptr 的值是 0
On most operating systems, the program does not allow access to memory address 0, because the memory is reserved for the operating system. However, the memory address 0 has a special significance, it indicates that the pointer does not point to an accessible memory location. But according to the convention, if the pointer contains a null value (zero value), it is assumed that it does not point to anything.
To check for a null pointer, you can use the if statement, as follows:
if(ptr) /* 如果 p 非空,则完成 */ if(!ptr) /* 如果 p 为空,则完成 */
Therefore, if all unused pointers are assigned a null value, while avoiding the use of a null pointer, it is possible to prevent the misuse of an uninitialized pointer. In many cases, uninitialized variables there are some garbage value, causes the program difficult to debug.