【问题标题】:How do I correct this allocation error如何更正此分配错误
【发布时间】:2013-10-22 00:48:19
【问题描述】:

我想创建一个嵌套循环,循环遍历动态分配的数组(故事)找到字符“*”,并用来自另一个动态分配的数组(user_input)的信息填充此字符所在的位置。然后将这个替换信息存储在一个新的动态分配的数组中,称为body to be cout。 这是错误:

1>          with
1>          [
1>              _Elem=char,
1>              _Traits=std::char_traits<char>,
1>              _Alloc=std::allocator<char>
1>          ]
There is no context in which this conversion is possible

谁能告诉我我做错了什么? 这是我的代码:

void create_story(string & user_inputs, string *story, int num_lines,
        string **body)
{
    *body = new string[num_lines];

    for (int i = 0; i < story[i].length; i++)
    {
        if (story[i] == "*")
        {
            body[i];
        }

        for (int j = 0; j < story[i].length(); j++)
        {
            if (story[i][j] == '*')
            {
                cout << "I found it at character number: " << i;
                *body[i] += user_inputs;
            }
            else
            {
                body[i] += story[i][j];
            }
        }
    }
}

【问题讨论】:

    标签: c++ nested-loops dynamic-arrays


    【解决方案1】:

    这段代码有几个逻辑错误。

    1. 以下行对程序的状态没有影响(没有副作用)。

      body[i];

    2. 以下行不太可能正确终止,因为索引i 出现在不等式的两侧。

      for (int i=0; i&lt;story[i].length; i++)

    3. 上面的行可能无法编译,因为它比较了int 和成员函数 (length)。

    4. 下面这行测试整个第i行是否是简单的单星。

      if(story[i]=="*")

    我相信还有其他问题。你应该从更少的代码开始,看看你是否可以分步完成任务,而不是一次完成所有任务。会更容易理解。

    【讨论】:

      猜你喜欢
      • 2013-08-21
      • 2014-07-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-16
      • 2014-02-25
      相关资源
      最近更新 更多