2017-11-18 206 views
0

我寫了一個功能分區進行快速排序算法的元素進行排序cstrings數組Visual Studio的運行時檢查失敗#2 - 圍繞堆棧變量「臨時」被損壞

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複製到話

+0

'temp [MAXWORDLEN + 1]'爲'\ 0'? – coderredoc

+0

@coderredoc是的,所以我可以使用c函數 –

+0

在'if'語句內部也使它相同...這就是我的意思。 '臨時[MAXWORDLEN + 1]' – coderredoc

回答

1

改變這樣的:因爲樞軸陣列具有

char temp[MAXWORDLEN + 1]; 

char temp[MAXWORDLEN]; 

本這個大小也是。


所以當temp是大小爲6,它包含有6個字符單詞,空終止將被重寫,這意味着複製會失敗,並調用未定義的行爲。我們真的不知道要通過複製將什麼垃圾值寫入目標數組,如果有的話。

+0

不錯@coderredoc ,,但我認爲這是問題的答案。 – gsamaras

相關問題