gpt4 book ai didi

C++ 字符串大小在循环期间发生变化

转载 作者:行者123 更新时间:2023-11-27 22:48:53 26 4
gpt4 key购买 nike

我的程序假设读取一个字符串,然后将每个字符插入堆栈。我注意到,当我打印 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] - 它也不存在。

当行为未定义时(如上所示),任何事情都可能发生。包括似乎覆盖不相关的数据或(在您的情况下)覆盖 main() 中的字符串 word 的部分。

您需要更好地阅读 C++ 的基础知识,而不是猜测其工作原理。你猜错了。

关于C++ 字符串大小在循环期间发生变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39812965/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com