I'm trying to figure out an implementation of an array-based queue in c++. At this point I'm just trying to initialize an array with a size dependent on what the user inputs. I have a Queue class as follows:
Queue.h: #include
using namespace std;
class Queue {
private:
int *ptrtoArray;
int arraysize;
int data;
public:
Queue(int size);
Queue();
void print();
};
Queue.cpp:
#include "Queue.h"
Queue::Queue() {
}
Queue::Queue(int size) {
int theQueue[size];
arraysize = size;
ptrtoArray = &theQueue[0];
for (int i=0;i<size;i++) {
theQueue[i] = -1;
}
cout << "(";
for(int i=0;i<size;i++) {
cout << ptrtoArray[i] << ",";
}
cout << ")" << endl;
}
void Queue::print() {
cout << "(";
for(int i=0;i<arraysize;i++) {
cout << ptrtoArray[i] << ",";
}
cout << ")" << endl;
}
main.cpp:
#include <iostream>
#include "Queue.h"
using namespace std;
const string prompt = "queue> "; // store prompt
Queue *queue;
void options(){
string input; // store command entered by user
cout << prompt; // print prompt
cin >> input; // read in command entered by user
int queuesize,num;
while(input != "quit") { // repeat loop as long as user does not enter quit
if (input == "new") { // user entered ad
cin >> queuesize;
queue = new Queue(queuesize);
} else if (input == "enqueue"){ //user entered remove
} else if (input == "dequeue"){ //user entered remove
} else if (input == "print"){ //user entered quit
queue->print();
} else { // no valid command has been selected
cout << "Error! Enter add, remove, print or quit." << endl;
}
cout << prompt; // repeat prompt
cin >> input; // read new input
}
}//options
/**
* Main function of the program. Calls "options", which handles I/O.
*/
int main() {
options();
return 0;
}
When the code is executed everything is fine with the code inside the constructor, but the print function is giving some strange results.
queue> new 5
(-1,-1,-1,-1,-1,)
queue> print
(134516760,134525184,-1081449960,4717630,134525184,)
queue>
So, at this point I just want the print() function to show me that the array contains just -1 in every element. My knowledge of pointers is very limited, so if you could help me realize what I'm doing wrong that would be great!