指向数组的指针未按预期工作

Pointer to an array isn't working as intended

本文关键字:工作 指针 数组      更新时间:2023-10-16

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

队列.h:#包括

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

当代码被执行时,构造函数内的代码一切都很好,但print函数给出了一些奇怪的结果。

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

因此,在这一点上,我只想让print((函数向我表明,数组在每个元素中只包含-1。我对指针的了解非常有限,所以如果你能帮助我意识到我做错了什么,那就太好了!

您在本地作用域中声明您的数组,然后在它脱离作用域时丢失它,但指针仍然指向它在内存中的地址,谁知道它会变成什么样子,正如您所发现的那样。尝试:

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

new关键字:

ptrToArray = new int[size];
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;

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

这是意料之中的事。请参阅,class QueueptrtoArray成员指向一个函数范围变量,该变量在程序的整个生命周期内都不可用。给,这是你的构造函数。因此ptrtoArray将指向一个完全随机的内存位置,即所谓的"野生指针">

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