我编写了一个函数来划分元素,用于对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的单词中
发布于 2017-11-18 04:53:07
改变这一点:
char temp[MAXWORDLEN];对此:
char temp[MAXWORDLEN + 1];因为枢轴数组也有这个大小。
因此,当temp大小为6并且它包含的单词有6个字符时,空终止符将被覆盖,这意味着复制将失败并调用未定义的行为。我们并不知道要通过复制(如果有的话)将哪些垃圾值写入目标数组。
https://stackoverflow.com/questions/47362574
复制相似问题