プログラムでは、文字列を読み取り、各文字をスタックに挿入することを想定しています。私は、単語のサイズであるlength
を印刷すると気付きましたが、それは高い数字に変わります。たとえば、word = "hello"
の長さは最初は5
になりますが、最終的には= 111
に変更されます。また、私は2つの文字を使用すると、私はいつもセグメンテーション違反を取得します。これを引き起こしているのは何ですか?なぜ言葉の長さは変わるのですか?ループ中にC++の文字列サイズが変更される
#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()
{
}
}
あなたの宣言を 'char arr []'から 'char arr [STACK_CAPACITY]' –
"arr [STACK_CAPACITY];に変更してください。無意味な陳述であり、絶対に何もしません。 'arr'は長さ0の配列のままです。文字を追加しようとすると、未定義の動作とメモリ破損が発生します。 –
なぜあなたはstlを嫌いですか? std :: stackを使用してください。 –
Bonan