这是我的代码,我不明白为什么我得到运行时检查失败#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;
}
答案 0 :(得分:6)
constructSet
将x
设置为12 swap
的循环的第一次迭代将尝试写入tempSign[12]
。 C数组从零开始,因此tempSign
的有效索引为[0..11]。写入元素12是未定义的行为,但可能会在堆栈上乱写,直到超出为tempSign
分配的内存的末尾。
您可以通过更改swap
tempSign[x-1]=temp;
// ^^