奇怪的临时阵列损坏

1 c++ arrays corrupt

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

Stack around the variable "temp" was corrupted
Run Code Online (Sandbox Code Playgroud)

变量的片段在嵌套的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;
    }
}
Run Code Online (Sandbox Code Playgroud)

text作为字符串在for循环之外初始化,当我将temp [1]变为char或int时,我得到相同的错误.该程序工作正常,但我担心为什么我收到此错误,有谁知道为什么?

Ree*_*sey 15

你只需要使用char temp;和访问它temp = text[i];等.

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


Sim*_*hes 10

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

char temp;
temp = text[i];
text[i] = text[j];
text[j] = temp;
Run Code Online (Sandbox Code Playgroud)

要么

char temp[1];
temp[0] = text[i];
text[i] = text[j];
text[j] = temp[0];
Run Code Online (Sandbox Code Playgroud)


cob*_*bal 7

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