0

我正在尝试在 C++ 中找出基于数组的队列的实现。在这一点上,我只是试图初始化一个大小取决于用户输入的数组。我有一个队列类如下:

队列.h:#include

using namespace std;

class Queue {

    private:
        int *ptrtoArray;
        int arraysize;
        int data;
    public:
        Queue(int size);
        Queue();
        void print();


};

队列.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;
}

主.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;
}

执行代码时,构造函数中的代码一切正常,但 print 函数给出了一些奇怪的结果。

queue> new 5
(-1,-1,-1,-1,-1,)
queue> print
(134516760,134525184,-1081449960,4717630,134525184,)
queue>

所以,此时我只想让 print() 函数告诉我数组中的每个元素都只包含 -1。我对指针的了解非常有限,所以如果你能帮助我意识到我做错了什么,那就太好了!

4

3 回答 3

3

你在本地范围内声明你的数组,然后在它超出范围时丢失它,但指针仍然指向它在内存中的地址,谁知道它会变成什么,正如你所发现的那样。尝试:

ptrToArray = (int *) malloc(sizeof(int) * size);

new关键字:

ptrToArray = new int[size];
于 2013-03-31T18:20:12.197 回答
2
int theQueue[size];
arraysize = size;
ptrtoArray = &theQueue[0];

分配theQueue将在构造函数返回时释放的静态数组。您应该改为分配动态数组new

arraysize = size;
ptrtoArray = new int[size];

不要忘记在你的析构函数中删除它(如果你不再需要它,或者更早)。


编辑

静止的

int theQueue[size];

将在堆栈上分配。这意味着当您的函数(声明所在的位置)返回时,内存不再可访问。例如,下一个函数可以使用它来保存另一个数组。

优势更快,您不必显式释放它,从而避免泄漏。

动态的

ptrtoArray = new int[size];

在堆上分配。这意味着即使您超出范围,它仍将归您所有(除非您丢失指向它的指针。在这种情况下,您注定要失败)。如果您不再需要它,您可以使用

delete[] ptrtoArray;

优势可以具有动态大小。超出范围可用。

于 2013-03-31T18:20:57.603 回答
0

这实际上是预期的。看,指向函数范围变量的ptrtoArray成员,class Queue在程序的整个生命周期中都不可用。在这里,那是你的构造函数。所以ptrtoArray将指向一个完全随机的内存位置,即所谓的“野指针”

请参阅:https ://stackoverflow.com/a/11137525/1919302 ,以更好地了解变量的作用域和生命周期之间的区别以及为什么您的输出是这样的。

于 2013-03-31T18:22:13.123 回答