【问题标题】:Runtime error in c++. Relocation protocol version %dc++ 中的运行时错误。重定位协议版本 %d
【发布时间】:2017-04-24 13:01:40
【问题描述】:

请帮我解决以下转换 spoj here is the link 表达式的问题。它给出了运行时错误。

     #include <iostream>
     #include <stack>
#include <string>
using namespace std;
int main()
{
    int testcases;
    cin >> testcases;
    while(testcases-->0)
    {
        string s;
        cin >> s;
        cout << s;
        stack<string> st;
        for(int i=0;i<s.length();i++)
        {
            if(s.at(i)=='(')
                continue;
            else
                if(s.at(i)==')')
                {
                    string s2=st.top();
                    st.pop();
                    string expression=st.top();
                    st.pop();
                    string s1=st.top();
                    st.pop();
                    string tba=s1+s2+expression+"";
                    st.push(tba);
                    cout << tba << endl ;
                    }
            else
                st.push(s.at(i)+"");
                }

        string ss=st.top();
        cout << ss;
        }

    }

而且即将出现的错误是无法理解的。 以下是第一行和第二行输入的错误。

1
(a+(b*c))
(a+(b*c))do relocation protocol version %d.
o relocation protocol version %d.
uery failed for %d bytes at address %p
udo relocation protocol version %d.
do relocation protocol version %d.
o relocation protocol version %d.
uery failed for %d bytes at address %pery failed for %d bytes at address %p
udo relocation protocol version %d.
do relocation protocol version %d.
o relocation protocol version %d.
uery failed for %d bytes at address %pery failed for %d bytes at address %p

【问题讨论】:

  • 你想做什么?预期的输出/输入是什么?尽可能准确地描述您的问题。目前这个问题可能应该被关闭。
  • 问题陈述是:spoj.com/problems/ONP
  • 检查程序的输入测试用例"()"。还要检查这些:如果堆栈为空并且您尝试访问top() 怎么办? top() 会在空堆栈上返回什么?
  • s.at(i)+"" 并没有按照你的想法去做。

标签: c++ stack protocols relocation


【解决方案1】:

看起来您已经成为 Java 主义的牺牲品。

char ch = 'a';
string str = value + "";

不会使string str "a"。

这是因为"" 不是string。它实际上是一个指向常量字符数组的指针,const char *,因为它是一个指针,所以会发生指针运算。

"" 是内存中的某个位置。假设地址为 10000。'a' 有一个数值。让我们坚持使用 ASCII 并使用 97。value + ""; 告诉编译器转到地址 10000 + 97,没有人知道它会在地址 10097 找到什么。但它是一个const char *,并且string 有一个构造函数将采用const char * 并尝试将其转换为string。无论发生在 10097 处的什么,都将用于生成 string。这可能会使程序崩溃。它还可以从字符串文字的土地上抓取垃圾,这看起来就是 OP 正在发生的事情。

解决方案:

构造一个string

string str(1, ch);

或者在 OP 的情况下,

st.push(string(1, s.at(i)));

Documentation on string constructor见构造函数2。

但要小心。您的开发环境几乎肯定会出现一堆其他逻辑错误best resolved by using the debugging software

【讨论】:

  • 你的意思是如果我做 stack.push('a'+""),那么这将被认为是 stack.push(const char *) 并且它会使程序崩溃。对吗?
  • 不完全是,@PatelParth。它仍然是 stack.push(string),但 string 是由 'a'+"" 组成的,这是错误的,并且可能致命,const char *
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-01-12
  • 2020-06-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多