+ 1

Error in "Queue Management Part 1," C++ Intermediate

I was trying to solve a Code Coach. The class was already created, the other methods were already there and stuff. The prompt was to create an "add" method for the Queue class so that you can add an item to the end of a queue. Here's the whole code: ______________________________________________________________________________ #include <iostream> using namespace std; class Queue { int size; int* queue; int increment; public: Queue() { size = 0; queue = new int[100]; } void remove() { if (size == 0) { cout << "Queue is empty"<<endl; return; } else { for (int i = 0; i < size - 1; i++) { queue[i] = queue[i + 1]; } size--; } } void print() { if (size == 0) { cout << "Queue is empty"<<endl; return; } for (int i = 0; i < size; i++) { cout<<queue[i]<<" <- "; } cout << endl; } //your code goes here void add(int x) { queue[increment] = x; increment++; size++; } }; int main() { Queue q; q.add(42); q.add(2); q.add(8); q.add(1); q.print(); q.remove(); q.add(128); q.print(); q.remove(); q.remove(); q.print(); return 0; } ______________________________________________________________________________ And for some reason, it returns "timeout: the monitored command dumped core". It's one I haven't seen before, what's causing it?

29th Jan 2023, 11:00 PM
Favor
Favor - avatar
2 Antworten
+ 5
you are using increment variable without initializing it first, then you are incrementing it which results in an Undefined Behavior. just replace increment with size .
29th Jan 2023, 11:32 PM
Bahhaⵣ
Bahhaⵣ - avatar
+ 2
Yeah, it works perfectly now. Thanks!
30th Jan 2023, 12:34 AM
Favor
Favor - avatar