well, first of all, as Jonathon said, there is no guarantee that the array will be initialized to 0
. You can either initialize it separately, or use int *x = new int[5]();
which would do initialization for you.
As for how do you know which are valid. The simplest approach is to store a struct instead of int
s. Something like this:
struct T {
T() : valid(false), value(0) {
}
bool valid;
int value;
};
T *p = new T[5]; // each element will be initialized to false/0 because T has a constructor.
Then you can just do:
p[0].value = 10;
p[0].valid = true;
and so forth.
EDIT:
As a more advanced option, you can use operator overloading to make the valid
flag get set automatically like this:
struct T {
T() : valid(false), value(0) {
}
T &operator=(int x) {
valid = true;
value = x;
return *this;
}
bool valid;
int value;
};
T *p = new T[5]; // each element will be initialized to false/0 because T has a
p[1] = 10; // p[1] is now true/10
Basically, assigning an integer value to the element, will automatically mark it as valid. Though in this particular example, I have not demonstrated how to "unset" a value back to being "invalid". This may or may not make sense for your use case or coding style, just some food for thought.