簡體   English   中英

計算C中的排序分段錯誤

[英]Counting sort segmentation fault in C

以下是我對計數的嘗試。 我已經繪制了邏輯示意圖,進行了口頭陳述,並徹底注釋了我的代碼。 但是,我的代碼導致分段錯誤。 我知道分段錯誤代表對內存的非法訪問,因此這必須表示我的索引值之一正在嘗試訪問數組范圍之外的索引。 但是,我不知道為什么會這樣。

幸運的是,我的調試器突出顯示了下面的行,我也在注釋中指出了發生分段錯誤的行。 不過,我完全感到沮喪。 希望能幫助您理解此細分錯誤的性質,謝謝。

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;
}

您需要將countArray元素初始化為零以修復崩潰:

int countArray[INT_MAX] = {0};

但是,您的函數仍然沒有用,因為它會將排序后的數字放入一個永遠不會使它脫離函數的本地數組。 為了解決此問題,請刪除sortedValues數組,並使用原始values數組作為輸出:

values[sortedIndex] = j;

現在,調用者將看到他傳遞給您的函數的數組返回已排序。

注意:外循環while(sortedIndex < n)是無害的,但沒有用,因為for循環保證sortedIndex恰好是n 您應該從代碼中刪除while循環。

如前所述,您不需要為sortedIndex設置單獨的循環。

而且,正如@dasblinkenlight所建議的那樣,您無需創建本地數組sortedValue即可存儲排序后的值,而可以對數組values進行排序。

另外,您需要用全零初始化countArray以避免索引垃圾值。

這是代碼:

void sort(int values[], int n)
{
    //create array of finite size (65536)
    int countArray[INT_MAX] = {0};

    //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 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[]
     values[sortedIndex] = j;

     //decrease the count of countArray[j] once value appended to sortedValues[]
     c -= 1;

     //move to next index of sortedValues[]
     sortedIndex += 1;
    }
   }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM