我已经编写了一个函数来对元素进行分区,以用于对 cstring 数组进行排序的快速排序算法
void partition(char words[][MAXWORDLEN + 1], int start, int end, int& partitionIndex) {
char pivot[MAXWORDLEN + 1]; //choose last element to be the pivot
strcpy(pivot, words[end]);
partitionIndex = start; //partition index is initalized to the first index
for (int i = start; i < end; ++i) { //iterate through the array
if (strcmp(words[i], words[end]) < 0) {
char temp[MAXWORDLEN];
strcpy(temp, words[i]); //swap the element with the element corresponding to the partition index
strcpy(words[i], words[partitionIndex]);
strcpy(words[partitionIndex], temp);
partitionIndex++;
}
}
cout << end << endl;
char temp[MAXWORDLEN + 1];
strcpy(temp, words[end]);
strcpy(words[end], words[partitionIndex]);
strcpy(words[partitionIndex], temp);
但是,当我运行该程序时,出现运行时检查失败。 MAXWORDLENGTH 为 6,数组中所有单词的长度都在 4-6 个字符之间。所以我很困惑为什么变量 temp 似乎无法复制到索引 partitionIndex 处的单词
最佳答案
改变这个:
char temp[MAXWORDLEN];
为此:
char temp[MAXWORDLEN + 1];
因为枢轴数组也有这个大小。
因此,当 temp
的大小为 6 并且它包含的单词有 6 个字符时,空终止符将被覆盖,这意味着复制将失败并调用未定义的行为。我们真的不知道通过复制将哪些垃圾值写入目标数组(如果有的话)。
关于c++ - Visual Studio 运行时检查失败 #2 - 变量 'temp' 周围的堆栈已损坏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47362574/