I am trying to write a simple function that fills an array of object pointers by detecting NULL indexes and creating new objects.
Wire *wireArray[MAX_WIRES];//The array is of class "Wire" and returns a pointer to a wire object.
Wire *getWirePtrFromWireNum(int num); //the function gets the index to the array and returns a NULL if empty and the pointer if it is not NULL.
In the following if-statement, I tried to pass the index to the function and create a new Wire object if the array at that number is NULL.
if (getWirePtrFromWireNum(wirenum) == NULL) {
Wire newWire;
wireArray[wirenum] = &newWire;
}
The function for the getWirePtrFromWireNum simply checks for the NULL index and returns the pointer if it is occupied.
Wire * Circuit::getWirePtrFromWireNum(int num)
{
if (wireArray[num] == NULL) {
return NULL;
}
else {
return wireArray[num];
}
}
When I test it with a several inputs, it does not enter first if-statement at all. I did not feel the need to initialize the pointer array to NULL, but I feel like it should still be catching that the first indexes should be empty. The code does not return any errors, but the function does not seem to be doing what it should be. Where could my error be coming from?
EDIT:
for (int i = 0; i < MAX_WIRE; i++) {
wireArray[i] == NULL;
}
Fixed Function:
Wire * Circuit::getWirePtrFromWireNum(int num)
{
if (wireArray[num] == NULL) {
wireArray[num] = new Wire;
return wireArray[num];
}
return wireArray[num];
}