-4

这是我的代码,我不明白为什么会出现运行时检查失败 #2 - 变量“tempSign”周围的堆栈已损坏。我相信错误是由于尝试在 char* tempSign [MAX] 中交换 2 个值而引起的。有人可以解释为什么我会收到此错误并帮助我解决此问题,谢谢。

void constructSet(ZodiacSign *& z,int size)
{

    /*ZodiacSign is a char *
     This is how z was created from the previous function and 
     passed by reference

     ZodiacSign * z;
     z=new char* [num];

    for (int i=0;i<num;i++)
    {
        z[i]=new char [MAXSTR]; 
    } */

    ZodiacSign tempSign [MAX]={"aquarius","pisces","aries","taurus","gemini","cancer","leo",
                               "vergo","libra","scorpio","sagittarius","capricorn"};


    for (int i=0; i<size;i++)
    {
        int x=12;
        int num=(rand()%x);

        char * ptr=tempSign[num];
        strcpy(z[i],ptr);
        swap(num,x,tempSign);

        x--;
    }
}

void swap(int num,int x,ZodiacSign tempSign [MAX])
{
    ZodiacSign temp;

    temp=tempSign[num];

    tempSign[num]=tempSign[x-1];

    tempSign[x]=temp;
}
4

1 回答 1

6

循环的第一次迭代constructSet设置x为 12. swap然后将尝试写入tempSign[12]. C 数组是从零开始的,因此有效索引为tempSign[0..11]。写入元素 12 是未定义的行为,但很可能会在刚刚超出为tempSign.

您可以通过更改以下行来解决此问题swap

tempSign[x-1]=temp;
//        ^^
于 2013-01-30T15:13:56.417 回答