Reputation: 683
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
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
Reputation: 172398
Initialize the array:- cPlayer* players[MAX_PLAYERS] = {};
Upvotes: 3
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
Reputation: 103693
Initialize your pointers to null pointers, which can be done like this:
cPlayer* players[MAX_PLAYERS] = {};
Upvotes: 10