Следующая программа успешно создает stack
, но две операции pop
и stack top
дают исключение и неверный результат соответственно. Вот программа:
// Working with stack using Array
/*
* @author Suhail Gupta
*
*/
#include <iostream>
using namespace std;
char choice;
int *ptrToArray; // this will be a pointer to the array alias stack that we'll make
int stackSize;
int currentStackSize = 0;
int *firstElement = NULL; // this pointer stores the address of the first element in the stack. It initially points to NULL
void push();
void pop();
void stackTop();
int main() {
cout << "Enter the size of stack : ";
cin >> stackSize;
ptrToArray = new int[stackSize];
do {
push();
cout << "Push elements ? y/n ";
cin >> choice;
} while( choice == 'y');
cout << endl << "pop elements ? y/n ";
cin >> choice;
if( choice == 'y') {
pop();
}
cout << endl << "know the stack top ? y/n ";
cin >> choice;
if( choice == 'y') {
stackTop();
}
}
void push() {
if( currentStackSize == stackSize) { // check before pushing if the stack is full
cout << endl << "Stack-Overflow !";
} else {
int numberToPush;
cout << endl << "Enter the number to be pushed : ";
cin >> numberToPush;
firstElement = &numberToPush; // Store the address of the Last number inserted.This is the address of the first element in the stack
ptrToArray[currentStackSize] = numberToPush;
cout << "The element you just inserted : " << ptrToArray[currentStackSize] << endl;
currentStackSize++;
}
}
void pop() {
if( stackSize == 0 ) {
cout << "Stack Underflow !";
} else {
delete firstElement; // delete the memory allocated to the first element
firstElement = &ptrToArray[currentStackSize-1];
currentStackSize--;
}
}
void stackTop() {
if( firstElement == NULL) {
cout << endl << "Stack Underflow !" << endl;
} else {
cout << "The first element in the stack is : " << *firstElement;
}
}
Операция нажатия работает нормально. Но если я вызываю функцию pop
, отображается следующее сообщение:
Второй вопрос:
Теперь просто прокомментируйте оператор, в котором вызывается функция pop
. Результат, который я получаю, когда пытаюсь узнать первый элемент в стеке, вызывая функцию stackTop()
, равен The first element in the stack is : -858993460
. Это какой-то garbage number
, в который я не вошел, составляя stack
. Почему утверждение *firstElement
дает неверный результат?