rubenwardy
rubenwardy

Reputation: 683

See if a pointer in an array is empty (c++)

I have an array of pointers to a class called cPlayer.

Compiler: Visual C++ 2010 Express

Init

cPlayer* players[MAX_PLAYERS];

Max_Players is a defined value of 10. defined in a class called "OnlineData", in a header.

Checking

if (players[a]){
   // some code here
}

What ever I have tried, it still gets through to //some code here

Players are deleted like this:

players[player->id]=0;
delete player;

Question

I want to check if item at position a in the players array has a value. I am using it to resort the player list (defragmentation)

The array works normalling in adding content, until i try to do the above thing

Upvotes: 3

Views: 2145

Answers (5)

bames53
bames53

Reputation: 88155

To initialize a global or local array you would use:

cPlayer* players[MAX_PLAYERS] = {};

However since your array is a class member you can't do this (until C++11 introduced in-class initialization, but VS2010 does not support this feature). Instead you have to write code that initializes each member individually in your constructor bodies (or init function or whatever):

struct S {
    cPlayer *players[MAX_PLAYERS];

    S() {
        for (int i=0; i<MAX_PLAYERS; ++i) {
            players[i] = NULL;
        }
    }
};

Or better than using an explicit loop would be to use something from <algorithm>, such as std::fill or std::fill_n:

std::fill_n(players, MAX_PLAYERS, NULL);

Upvotes: 8

Anirudha
Anirudha

Reputation: 32787

Use

std::fill_n(players, 10, 0)

to initalize all members to 0..

Upvotes: 0

Rahul Tripathi
Rahul Tripathi

Reputation: 172398

Initialize the array:- cPlayer* players[MAX_PLAYERS] = {};

Upvotes: 3

Rontogiannis Aristofanis
Rontogiannis Aristofanis

Reputation: 9063

Initialize all the values of the array to NULL (found at <cstdlib>). Then, when you want to assign a value to one of the positions of the array, write: players[i]=new cPlayer(...). To check if a position a is empty, simply check if players[a]==NULL.

Upvotes: 1

Benjamin Lindley
Benjamin Lindley

Reputation: 103693

Initialize your pointers to null pointers, which can be done like this:

cPlayer* players[MAX_PLAYERS] = {};

Upvotes: 10

Related Questions