【问题标题】:Strange temporary array corruption奇怪的临时数组损坏
【发布时间】:2009-03-14 20:26:34
【问题描述】:

我正在尝试创建一个排列,当我完成我的问题时收到这个奇怪的错误:

Stack around the variable "temp" was corrupted

变量的段在嵌套的for循环中:

for(int i = 0 ; i < str_length ; i++)
{
    for(int j = 0 ; j < str_length ; j++)
    {
        char temp[1];

        temp[1] = text[i];
        text[i] = text[j];
        text[j] = temp[1];

        cout << text << endl;
    }
}

文本在 for 循环之外被初始化为字符串,当我将 temp[1] 转换为 char 或 int 时,我得到了同样的错误。该程序运行良好,但我担心为什么会收到此错误,有人知道为什么吗?

【问题讨论】:

  • 如果您想要独特的排列,请考虑使用for(int j = i + 1;

标签: c++ arrays corrupt


【解决方案1】:

您只需要使用char temp; 并将其访问为temp = text[i]; 等即可。

您正在访问堆栈上一个字节的 PAST temp 点,这是无效的。在这种情况下,由于您只需要一个字符,因此根本不需要数组。

【讨论】:

    【解决方案2】:

    temp[1] 不存在,你应该做 temp[0]。或者,像这样:

    char temp;
    temp = text[i];
    text[i] = text[j];
    text[j] = temp;
    

    char temp[1];
    temp[0] = text[i];
    text[i] = text[j];
    text[j] = temp[0];
    

    【讨论】:

      【解决方案3】:

      使用temp[0] 访问第一个元素

      【讨论】:

        猜你喜欢
        • 2012-11-17
        • 2011-08-20
        • 2016-12-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-04-14
        • 2020-02-26
        相关资源
        最近更新 更多