Weird array properties
-
I am currently trying to manipulate an array being used as a queue.
int Elevator::move(){ if (queueSize > 0) { //qInfo("Trying to change to floor %d", queue[0]); setFloor(queue[0]); //qInfo("Current floor: %d", getFloor()); printQueue(); for(int i = 0; i < 20-1; ++i) { queue[i] = queue[i + 1]; } printQueue(); //qInfo("Next floor: %d", queue[0]); queueSize--; return queueSize; } else { qInfo("No floors in queue."); return -1; } }
I filled the queue with 3 floors. After moving to the first floor, the array gets shifted perfectly fine. The issue is when the queue gets accessed the next time, the index 0 of the array will always get changed back to the first floor request.
Here is the console output (The first print of each cycle is the queue before changing floors, the second one is the queue after changing)
Printing Queue: 3 4 5 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 Printing Queue: 4 5 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2 left in queue inside moveElevator1 Printing Queue: 3 5 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 Printing Queue: 5 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 left in queue inside moveElevator1 Printing Queue: 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 Printing Queue: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 left in queue
The array I'm using is simply "int queue[20] ;"
Please let me know if you can see a problem here. I can provide more class declarations if needed.
-
Hi,
The printQueue code would be nice to have as well.
You should also check for any code setting values in your queue.
Finally, why not use a queue class such as QQueue ?
-
@ItsRhysNotRhys
In order to get fromPrinting Queue: 4 5 0
to
2 left in queue inside moveElevator1 Printing Queue: 3 5 0
something outside the code you are showing us (maybe in whatever issues two of those message lines) is writing
3
toqueue[0]
. Either directly, or just possibly through buffer over/underflow writing to another member variable adjacent toint queue[20]
.