2014-04-04 87 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)页面似乎暗示 –