C++ Null Pointer
When declaring a variable, if there is no exact address to assign, it is a good programming practice to assign a NULL value to the pointer variable. A pointer assigned a NULL value is calledEmptypointer.
A NULL pointer is a constant with a value of zero defined in the standard library. Look at the following program:
Example
using namespace std;
int main ()
{
int *ptr = NULL;
cout << "The value of ptr is " << ptr ;
return 0;
}
When the above code is compiled and executed, it produces the following results:
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. But by convention, if a pointer contains 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 null values and the use of null pointers is avoided, misuse of an uninitialized pointer can be prevented. Often, uninitialized variables contain garbage values, making programs difficult to debug.
other extensions