C++ 数组中的元素发生了异常更改
代码块17.12,win10 数组“theQueue”的第二个元素在main函数中的“cin>>theNumber;”行前后显示不同 我通过在数组“theQueue”的元素之前和之后添加“Q.display();”来发现问题 此外,在函数“bool Queue::enqueue(int number)”中,变量“sequence”也发生了异常变化C++ 数组中的元素发生了异常更改,c++,codeblocks,C++,Codeblocks,代码块17.12,win10 数组“theQueue”的第二个元素在main函数中的“cin>>theNumber;”行前后显示不同 我通过在数组“theQueue”的元素之前和之后添加“Q.display();”来发现问题 此外,在函数“bool Queue::enqueue(int number)”中,变量“sequence”也发生了异常变化 #include <iostream> using namespace std; class Queue { public: Q
#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;
}
#包括
使用名称空间std;
类队列
{
公众:
队列(内部大小);
布尔排队(整数);
int dequeue();
整数倍(整数倍)常数;
int getSize()常量;
void display()常量;
私人:
整数大小;
int队列[];
int sequence;//记录当前位置
};
int main()
{
int sizeValue,数字;
库兹瓦卢;
队列Q(sizeValue);
while(true)
{
Q.显示();
库特数;
Q.显示();
如果(Q.enqueue(编号)=false)
打破
}
cout队列
的大小为0。写入队列[0]
将产生未定义的效果,很可能写入序列字段(第0个数组元素和字段具有相同的大小和地址-gcc的实现)。写入或读取任何其他元素都会导致未定义的行为,可能会导致程序崩溃,而您显示的代码甚至不应该生成。不允许使用未大小的数组。如果您的编译器出于某种原因允许它作为扩展,那么它的大小仍将为零,并且所有索引都将超出范围。我更好奇的是,您为什么不这么认为他会工作。BTW,IDE是没有意思的;你会把编译器版本和标志使用,但是我们不需要这里,因为实际问题是显而易见的。未用的数组在C中使用,但是不同的方式。无论如何,在C++中没有理由使用它们(特别是它不是合法的C++代码)。@它是用gcc编译的,这是使一些C代码正确的扩展。