John Yuki
John Yuki

Reputation: 310

How to check whether an index in an array is empty

I'm making a small OpenGL program for my intro to C++ class in Uni. I have a program that is complete but I want to change it up a bit to make it more unique. I have a Cube class:

class Cube {
public:
    Cube(Mesh* mesh, Texture2D* texture, float x, float y, float z);
    ~Cube();
    void Draw();
    void Update(float rSpeed);
    Vector3 position;
private:
    GLfloat rotationSpeed;
    Vector3 rotationVector;
    Mesh* _mesh;
    Texture2D* _texture;
};

I then create an array of type Cube:

Cube* cubes[CUBE_AMOUNT];

I then fill each index of this array with data to draw the cube on screen later in the program:

for (int i = 0; i < CUBE_AMOUNT; i++) {
    float x = ((rand() % 400) / 10.0f) - 20.0f;
    float y = ((rand() % 200) / 10.0f) - 10.0f;
    float z = -(rand() % 1000);
    if (i % 2 == 1) {
        cubes[i] = new Cube(cubeMesh, textureStars, x, y, z);
    }
    else {
        cubes[i] = new Cube(cubeMesh, texturePenguins, x, y, z);
    }
}

With this new thing I want to add to the program, I want to check whether an index of cubes[] has been filled with the data yet. However I keep getting exceptions when running. I have tried to check whether cubes[i] is equal to nullptr, and tried checking whether it is NULL too, but neither seem to match.

Sorry for any errors in terminology that I used. New to C++, and having come from only doing Python before this, it is confusing!

Solution:

When I create the array, I changed it to Cube* cubes[CUBE_AMOUNT] = { NULL }, and now when checking the array, cubes[i] == NULL!

Upvotes: 0

Views: 127

Answers (3)

Ali Khaled
Ali Khaled

Reputation: 1

I think this would work

    //This bit should check if theres anything stored currently.
            cout << "\nWhich Slot would you like to store the informaton in ?(1-10)";
            cin >> i;
        i--;
        if (information[i] != NULL){
        // Already written 
            cout << "THERES SOMETHING HERE";
        }
    else{
      cout << "\nEMPTY!!!!!!!!!";
       }

Upvotes: 0

R Sahu
R Sahu

Reputation: 206567

If cubes is not a global variable, you can use:

Cube* cubes[CUBE_AMOUNT] = {};

to initialize all the elements to nullptr.

You can also use:

std::vector<std::unique_ptr<Cube>> cubes(CUBE_AMOUNT);

to remove the burden of having to deallocate dynamic memory in your code.

In either case, can use:

if ( cubes[index] )
{
   // Got a valid pointer. Use it.
}

Upvotes: 1

mipnw
mipnw

Reputation: 2325

Your cubes variable is not automatically initialized with null_ptr's. Until you either fill it with null_ptr's or good pointers it initially points to random garbage.

Upvotes: 0

Related Questions