C++ Null Pointer

Hi everyone, inside this article we will see about C++ Null Pointer.

In C++, a null pointer is a pointer that does not point to a valid memory address. The value of a null pointer is typically represented by the literal constant nullptr (or, in older C++ code, by the literal constant NULL).

A null pointer is often used as a placeholder to represent an uninitialized or invalid pointer, or to indicate that a function has failed to allocate memory.

Here is an example program that demonstrates how to use null pointers in C++:

#include <iostream>

using namespace std;

int main() {
  int *ptr1 = nullptr;  // A null pointer

  int *ptr2 = new int;  // Allocate memory for an integer

  if (ptr2 == nullptr) {
    cout << "Failed to allocate memory" << endl;
  } else {
    *ptr2 = 10;
    cout << "The value of the integer is " << *ptr2 << endl;
  }

  delete ptr2;          // Free the memory

  return 0;
}

In this program, we declare two pointers: ptr1 is initialized to nullptr, while ptr2 is allocated memory for an integer using the new operator.

We then check if ptr2 is a null pointer using an if statement. If ptr2 is null, we print an error message. Otherwise, we dereference ptr2 and assign the value 10 to it, and then print the value of the integer.

After we are done using the memory pointed to by ptr2, we free the memory using the delete operator.

Using null pointers can help prevent undefined behavior that can arise from dereferencing invalid pointers. However, it is important to note that even if a pointer is not null, it can still be invalid if it points to memory that has been freed or is outside the bounds of an allocated block of memory.

We hope this article helped you to understand about C++ Null Pointer in a very detailed way.

Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.