-4

通过注释堆栈语句运行代码时,它会产生正确的输出,但在声明堆栈时会显示分段错误。请帮忙。

#include <iostream>
#include <stack>
#include <queue>

using namespace std;

int main()
{
    int t;
    char *expr;

    stack < string > inp_stack;
    // queue <int> op_queue;

    cin >> t;

    while (t--)
    {

        cin >> expr;
        cout << expr << endl;
    }

    return 0;
}
4

2 回答 2

1
char *expr;
cin >> expr;

expr是一个未初始化(无效)的指针,使用它会导致未定义的行为

如果您想t从输入流中读取单词,请改用std::stringobject:

int t = 0;
std::cin >> t;

std::string expr;
while (t > 0 && std::cin >> expr) {
    std::cout << expr << std::endl;
}
于 2013-10-08T19:41:32.317 回答
0

It segfaults because you are accessing an uninitialized pointer. expr is never initialized so your program segfaults as soon as you access it.

You either need to allocate memory for expr or change it to a fixed size array.

于 2013-10-08T19:41:24.033 回答