Mein Programm soll eine Zeichenfolge lesen und dann jedes Zeichen in den Stapel einfügen. Ich bemerkte, wenn ich das length
drucke, das die Größe des Wortes ist, ändert es sich zu irgendeiner hohen Zahl. Zum Beispiel: word = "hello"
Länge wird = 5
zuerst aber schließlich zu ändern = 111
. Auch wenn ich 2 Buchstaben verwende, bekomme ich immer einen Segmentierungsfehler. Was verursacht das? Warum ändert sich die Länge des Wortes?C++ Stringgröße ändert sich während der Schleife
#include <iostream>
#include <string>
#include "Stack.h"
using namespace std;
int main()
{
Stack stack;
string word;
cout << "Enter word: ";
getline(cin, word);
cout << word << "|" << endl;
int length = word.size();
for (int i = 0; i < length; i++) {
cout << "i: " << i << "\tlength: " << length << endl;
stack.push(word[i]);
cout << "TOP: " << stack.top() << endl;
}
while (!stack.isEmpty())
{
cout << stack.pop();
}
cout << endl;
return 0;
}
#include <iostream>
#include <string>
#define STACK_CAPACITY 1000
using namespace std;
class Stack
{
private:
int topIndex;
char arr[];
public:
// Constructor
Stack()
{
arr[STACK_CAPACITY];
topIndex = -1;
}
// adds elements to "top" of array
void push(char c)
{
// if stack is full, do not add
if (isFull())
{
cout << "Push on full Stack" << endl;
// terminate function
}
topIndex++;
arr[topIndex] = c;
}
// Removes last inserted (push) element from the stack and returns it
char pop()
{
// checks if Stack is empty
if (isEmpty())
{
cout << "Pop on empty Stack" << endl;
return '@';
}
// if not empty, remove and return last element inserted
char temp = arr[topIndex];
arr[topIndex--] = ' ';
return temp;
}
// Returns but does not remove last inserted (push) element
char top() { return arr[topIndex]; }
// Utilities
bool isEmpty() { return topIndex == -1; }
bool isFull() { return topIndex == STACK_CAPACITY - 1; }
int size() { return topIndex + 1; }
// Destructor
~Stack()
{
}
}
Ändern Sie Ihre Deklaration von 'char arr []' in 'char arr [STACK_CAPACITY]' –
"arr [STACK_CAPACITY];" ist sinnlose Aussage und tut absolut nichts. 'arr' bleibt ein Array der Länge 0 und versucht, Zeichen hinzuzufügen, was zu undefiniertem Verhalten und Speicherkorruption führt. –
warum hasst du die stl? Verwenden Sie einfach std :: stack –
Bonan