C++循环期间字符串大小会发生变化
C++ string size changing during loop
我的程序假设读取一个字符串,然后将每个字符插入堆栈中。我注意到当我打印length
时,这是单词的大小,它变成了一些高数字。例如:word = "hello"
长度一开始将 = 5
,但最终更改为 = 111
。此外,当我使用 2 个字母时,我总是遇到分段错误。是什么原因造成的?为什么单词的长度会发生变化?
#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()
{
}
}
您的Stack
类中存在各种问题,导致它表现出未定义的行为。
例如,在构造函数中
Stack()
{
arr[STACK_CAPACITY];
topIndex = -1;
}
不会(我猜,您所期望的那样(调整arr
大小以具有STACK_CAPACITY
元素。 它试图评估arr[STACK_CAPACITY]
的值,因为arr
被声明为char arr[]
,所以不存在。 因此,该声明具有未定义的行为。
同样,push()
成员函数
// 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;
}
尝试(在第一次调用时(修改arr[0]
- 这也不存在。
当行为未定义时 - 如上文所示 - 任何事情都可能发生。 包括似乎覆盖不相关的数据或(在您的情况下(覆盖字符串word
的部分内容 main()
.
您需要更好地阅读C++的基础知识,而不是猜测事情是如何运作的。 你猜错了。
相关文章:
- 如何循环打印顶点结构
- 如何在C++中从两个单独的for循环中添加两个数组
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 正在尝试了解输入验证循环
- std::map<struct,struct>::find 找不到匹配项,但是如果我循环通过 begin() 到 end(),我在那里看到匹配项
- 循环后如何继续阅读
- Ardunio UNO解决了多个重叠的定时器循环
- Eigen如何在容器循环中干净地附加矩阵
- 如何避免LED在循环状态变化中闪烁?
- 如何在 c++ 中循环中使用频率变化的声音?
- for循环后,int值正在自行变化
- 在游戏更新循环中计算布尔的真/假变化
- 从 foreach 更改一对中的值不会显示循环外的变化
- C++地图上的循环没有检测到地图末端的变化
- 布尔值在 for 循环中没有变化
- 迭代器的指针在循环中如何变化C++
- c++的每个循环与变化的向量
- C++循环期间字符串大小会发生变化
- 循环中字符串的输出会根据是否满足某个条件而变化
- 循环后变量值突然发生变化