数组中的元素异常更改

时间:2018-04-24 13:40:28

标签: c++ codeblocks

CodeBlocks 17.12,win10

阵列的第二个元素" theQueue"在行之前和之后显示不同的" cin>> theNumber;"在主要功能。

我通过添加" Q.display();"找到了问题。之前和之后打印数组的元素" theQueue"。

此外,在函数" bool Queue :: enqueue(int number)"变量"序列"也不正常地改变了。

#include <iostream>

using namespace std;
class Queue
{
public:
    Queue(int theSize);
    bool enqueue(int number);
    int dequeue();
    int peek(int number) const;
    int getSize()  const;
    void display()  const;
private:
    int size;
    int theQueue[];
    int sequence;//record the current position
};
int main()
{
    int sizeValue,theNumber;
    cout<<"Enter the queue's size(less than 11): \n";
    cin>>sizeValue;
    Queue Q(sizeValue);
    while (true)
    {
        Q.display();
        cout<<"Please input a number to fill up the queue: \n";
        cin>>theNumber;
        Q.display();
        if (Q.enqueue(theNumber)==false)
            break;
    }
    cout<<"Now the queue have "<<Q.getSize()<<" elements,they are:\n";
    Q.display();
    cout<<"The first element in the queue is: "<<Q.dequeue()<<endl;
    cout<<"Now the queue have "<<Q.getSize()<<" elements,they are:\n";
    Q.display();
    return 0;
}
Queue::Queue(int theSize)
{
    int aQueue[10]={0,0,0,0,0,0,0,0,0,0};
    for (int i=0;i<10;i++)
         theQueue[i]=aQueue[i];
    size=theSize;
    sequence=0;//the initial position is 0
}
bool Queue::enqueue(int number)
{
    theQueue[sequence]=number;
    sequence=sequence+1;
    if (sequence>=size)
    {
        cout<<"The queue is full!\n";
        return false;
    }
    else
        return true;
}
int Queue::dequeue()
{
    int firstNumber;
    firstNumber=theQueue[0];
    for (int i= 1;i<size;i++)
         theQueue[i-1]=theQueue[i];
    size=size-1;
    return firstNumber;
}
int Queue::peek(int number) const
{
    return theQueue[number];
}
int Queue::getSize() const
{
    return size;
}
void Queue::display() const
{
    for (int j=0;j<size;j++)
         cout<<theQueue[j]<<" ";
    cout<<endl;
}

1 个答案:

答案 0 :(得分:0)

theQueue大小为0.写入theQueue[0]它会产生未定义的效果,最有可能写入sequence字段(第0个数组元素和字段具有相同的大小和地址 - gcc的实现)。写入或读取任何其他元素将导致未定义的行为,可能导致程序崩溃