How to declare an empty array in C++

Hello fellow learners! In this tutorial, we are going to learn and implement how to declare an empty array in C++.

Can I create an empty array in C ++?

You can’t create an array empty. An array has a fixed size that you can not change.  If you want to initialize the array you can put the value as 0 to create an empty array but an array cant have 0 sizes.

This can be done in multiple numbers of ways although here I would be discussing 2 main ways that are commonly used:

  • Declare an empty array that has a fixed size.
  • Declare an Empty Array with Fixed Size and Fixed Value.

Declare an empty array that has a fixed size

C++ Code

#include <iostream>

using namespace std;
 
int main()
{
    int EmptyArray[30]; // initializing an empty Array

    cout<<EmptyArray[0]; //print empty array

    return 0;
}

Output:

1709804328

Explanation of the Code:

First, we will declare an empty array with a fixed size ie 30 in this case. Next, we will not assign any value to the empty array and then we will print the output of the empty array the compiler will return a random value to avoid any runtime errors.

Declare an empty array with a fixed size and fixed value

C++ Code:

#include <iostream>

using namespace std;
 
int main()
{
    int emptyArray[15] = {0};  //initializing an empty std::array

    cout<<emptyArray[0]<<" "<<emptyArray[5]; //print output of the empty array

    return 0;
}

Output:

0 0

Explanation of the Code:

First, we need to initialize the array with a fixed size ie 15 in this case and assign the 0 value in it, rather than C++ compiler’s random value. So, the output of the empty array starting from zero will be printed.

Leave a Reply

Your email address will not be published.