Fin*_*ale 0 c segmentation-fault counting-sort cs50
以下是我对计数排序的尝试.我已经绘制了我的逻辑图,用口头表达,并彻底评论了我的代码.但是,我的代码会导致分段错误.我理解分段错误表示非法访问内存,因此这必然意味着我的一个索引值正试图访问数组范围之外的索引.但是,我无法弄清楚为什么会这样.
幸运的是,我的调试器突出显示了下面的行,我在评论中也注意到了这一点,其中发生了分段错误.尽管如此,我完全被难倒了.非常感谢任何帮助理解这个分段错误的性质,谢谢.
void sort(int values[], int n)
{
//create array of finite size (65536)
int countArray[INT_MAX];
//create array to eventually store sorted values
int sortedValues[n];
//loop through unsorted values to increment countArray index for each occurrence
for(int i = 0; i < n; i++) {
countArray[ values[i] ] += 1;
}
//starting index for sortedValues[]
int sortedIndex = 0;
//loop until we've reached the end of sortedValues[]
while(sortedIndex < n) {
//loop through each index value of countArray
//j represents the value
for(int j = 0; j < INT_MAX; j++) {
//how many times does the index of countArray occur in values[]?
int c = countArray[j];
//only add index j as a value to sortedValues[] if it appears in values[]
while(c > 0) {
//append j to sortedValues[]
//--SEGMENTATION FAULT OCCURS ON THE LINE BELOW--
sortedValues[sortedIndex] = j;
//decrease the count of countArray[j] once value appended to sortedValues[]
c -= 1;
//move to next index of sortedValues[]
sortedIndex += 1;
}
}
}
return;
}
Run Code Online (Sandbox Code Playgroud)
您需要将countArray元素初始化为零以修复崩溃:
int countArray[INT_MAX] = {0};
Run Code Online (Sandbox Code Playgroud)
但是,您的函数仍然无用,因为它将已排序的数字放入一个永远不会使其脱离函数的本地数组中.为了解决这个问题,请删除sortedValues数组,然后使用原始values数组作为输出:
values[sortedIndex] = j;
Run Code Online (Sandbox Code Playgroud)
现在调用者将看到他传递给你的函数的数组重新排序.
注意:外部循环while(sortedIndex < n)是无害的但无用,因为for循环保证sortedIndex完全正确n.您应该while从代码中删除循环.