Check if Any element in Array is NULL in C++

This tutorial will discuss about a unique way to check if any element in array is null in C++.

To check an array has any NULL value, we will use the std::any_of() function from STL Algorithms.

The std::any_of() function accepts three arguments,

  • Iterator pointing to the start of a sequence.
  • Iterator pointing to the end of a sequence.
  • A Callback or Lambda function which accepts a value of same type as the type of sequence, and returns a boolean value.

The std::any_of() function will apply the given Lambda function on all the elements of the sequence and it returns true if the callback function returns true for any element of sequence.

So, to check if an array of pointers contains a NULL value, we can use the std::any_of() function. i.e.

int* arr[] = {new int(5), nullptr, new int(7), nullptr, new int(3)};

// Check if there is any NULL value in the array
bool result = std::any_of(
                    std::begin(arr),
                    std::end(arr),
                    [](const int* ptr) {
                        return ptr == nullptr;
                    });

We passed three arguments in the std::any_of() function,

  • Iterator pointing to the start of array i.e. iterator returned by std::begin(arr).
  • Iterator pointing to the end of array i.e. iterator returned by std::end(arr).
  • A Lambda function which accepts an pointer as an argument, and returns true if the given pointer is NULL.

The any_of() function will return true, if there is any NULL Pointer in the array.

Let’s see the complete example,

#include <iostream>
#include <algorithm>

int main()
{
    int* arr[] = {new int(5), nullptr, new int(7), nullptr, new int(3)};

    // Check if there is any NULL value in the array
    bool result = std::any_of(
                        std::begin(arr),
                        std::end(arr),
                        [](const int* ptr) {
                            return ptr == nullptr;
                        });

    if (result)
    {
        std::cout << "Yes, Array has at least one NULL value " << std::endl;
    }
    else
    {
        std::cout << "No, Array does not have any NULL value " << std::endl;
    }

    // Free the memory allocated with new in array
    for (const int* ptr: arr)
    {
        delete ptr;
    }

    return 0;
}

Output :

Yes, Array has at least one NULL value

Summary

Today we learned about several ways to check if any element in array is null in C++. Thanks.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top