What is a null pointer in D?

Overview

A pointer is an address that points or references a variable in memory. In D programming, we allocate dynamic memory using pointers. The pointer references the address of the variable, unlike the usual direct referencing of the variable itself.

What is a null pointer?

A null pointer indicates that the address that has been referenced is invalid. Most operating systems have 0 reserved as a system address inaccessible by other programs.

A null pointer is important because it saves memory and reduces uninitialized spaces. Let's look at a good example.

Example

import std.stdio;
void main () {
int sed = 5;
int *pointer = &sed;
int *nullpointer = null;
writeln("The value of pointer is " , pointer) ;
writeln("The value of pointer is " , nullpointer) ;
}

Code explanation

  • Line 4: We declare a variable sed and assign a value to it. Pointers reference the address of a variable.
  • Line 5: We get the pointer of the sed variable
  • Line 6: We create a null pointer called nullpointer.
  • Line 8: We print the pointer of the sed variable to the screen. This is the storage location/address of the sed variable.