2014-04-04 88 views
0

我有以下計數排序功能奇怪的輸出用C

/* 
*File: countingSort.c 
*Description: A counting sort subroutine. Takes as input an array of integers. 
*    an array length and a range. All values in the input array must fall within     [0, range]. 
*   Takes O(range + arrayLen) time and O(range + arrayLen) extra space 
* 
*/ 

#include "countingSort.h" 

int* countingSort(int unsorted[], int arrayLen, int range) { 
    int store[range + 1]; 
    int sorted[arrayLen]; 

    for (int i = 0; i <= range; i++) { 
    store[i] = 0; 
    } 

    for (int i = 0; i < arrayLen; i++) { 
    sorted[i] = 0; 
    } 

    for (int j = 0; j < arrayLen; j++) { 
    store[unsorted[j]] ++; 
    } 

    for (int i = 1; i <= range; i++) { 
    store[i] += store[i-1]; 
    } 

    for(int j = arrayLen - 1; j >= 0; j--) { 
    sorted[store[unsorted[j]]] = unsorted[j]; 
    store[unsorted[j]] --; 
    } 

    return sorted; 
} 

的功能是給了我很奇怪的輸出。輸出大部分時間都不是輸入,但有時它是正常的。 這是怎麼回事?

我從所謂cSortTest.c另一個文件調用它。 這個文件看起來像這樣

/* 
*File: cSortTest.c 
*Description: Tests countingSort.c 
* 
*/ 

#include <stdio.h> 
#include "countingSort.h" 

int main() { 
    int data[8] = { 2, 1, 9, 4, 4, 56, 90, 3 }; 
    int* p; 

    p = countingSort(data, 8, 90); 
    for (int i = 0; i < 8; i++) { 
    printf("%d Element: %d\n", i, *(p+i)); 
    } 
} 

回答

3

你是返回一個本地數組變量。當函數退出時,該變量將被銷燬,從而使該地址不再安全或無法訪問。實際上訪問它會給你所謂的未定義的行爲,這解釋了它爲什麼有時看起來「工作」。

這是經典的初學者的在C.錯誤必須要麼有呼叫者傳遞所希望的目的地陣列中,或使用malloc()分配「持久」堆內存並返回:

int* countingSort(int unsorted[], int arrayLen, int range) { 
    int *sorted = malloc(arrayLen * sizeof *sorted); 
    if (sorted== NULL) 
    return NULL; 
    /* rest of sorting */ 
    return sorted; 
} 

arrayLen * sizeof *sorted表達計算分配所需的字節數。不需要使用清除內存的calloc();你要覆蓋每個元素,清除它只是浪費精力。

+0

我應該使用數組作爲頁頭()/釋放calloc()[這裏](http://www.codingunit.com/c-reference-stdlib-h-function-calloc)頁面似乎暗示 –