qsort不排序unsigned long int列表

时间:2015-01-31 11:57:29

标签: c sorting qsort

以下代码在尝试排序一系列无符号长整数时会产生奇怪的结果。我不知道为什么。它编译无警。问题出在我使用qsort的某个地方但是我已经把这条线扼杀了几个小时了。我认为我的比较功能还可以。我试图半盲地尝试所有可以想到的排列,以确保我传递正确的论据,但仍然没有骰子。任何帮助找到我的问题将不胜感激:

#include<stdio.h>
#include<stdlib.h>

#define LENGTH 10

static int cmpfunc (const void *a, const void *b) {
    const unsigned long int x=*(const unsigned long int*)a, y=*(const unsigned long int*)b;
    printf("x=%lu ",x); printf("y=%lu ",y);
    if ( x==y ) {
        puts("returning 0..."); return 0;
    } else {
        if ( x>y ) {
            puts("returning 1..."); return 1;
        } else {
            puts("returning -1..."); return -1;
        }
    }
}

int main(void) {
    /* declare the storage for our "array". Using malloc instead of [] because in
       real program array size shall be dynamic */
    unsigned long int *mystorage=malloc(LENGTH*sizeof(unsigned long int)); /* check for NULL */

    /* fill up array with values in non-monotonic order and show the values */
    for(unsigned long int counter=0;counter<LENGTH;counter++) {
        *(mystorage+counter*sizeof(unsigned long int))=(unsigned long int)(counter*(LENGTH-counter));
        printf("value is %lu\n",*(mystorage+counter*sizeof(unsigned long int)));
    }

    /* sort array */
    qsort(mystorage, LENGTH, sizeof(unsigned long int), cmpfunc);

    /* print out array again to see if it changed */
    for(unsigned long int counter=0;counter<LENGTH;counter++) {
        printf("value is %lu\n",*(mystorage+counter*sizeof(unsigned long int)));
    }

    exit(EXIT_SUCCESS);
}

2 个答案:

答案 0 :(得分:3)

*(mystorage+counter*sizeof(unsigned long int))
     =
         (unsigned long int)(counter*(LENGTH-counter));

...不正确。 (我稍微重新安排了你的空白。)它应该是

mystorage[counter] =
         counter*(LENGTH-counter); // the cast is redundant

以下三个是等效的:

mystorage[counter]
counter[mystorage]       // yes, this weird thing is equivalent
*(mystorage+counter)

将最后一行与您的代码进行比较。当您添加指针和整数时,编译器已经知道要移动正确的字节数。因为你包含sizeof东西,你有两个等效的行(与上面三行不同)

 *(mystorage + counter*sizeof(unsigned long int))
 mystorage[counter*sizeof(unsigned long int)]

应该很清楚,这两个将访问数组边界之外。

答案 1 :(得分:0)

你的程序在部分中是错误的

for(unsigned long int counter=0;counter<LENGTH;counter++) {
    *(mystorage+counter*sizeof(unsigned long int))=(unsigned long int)(counter*(LENGTH-counter));
    printf("value is %lu\n",*(mystorage+counter*sizeof(unsigned long int)));
}

当你向指针编译器添加一些整数时会自动使用地址算术,所以你不应该使用*sizeof(unsigned long int)。打印循环中出现同样的错误。因此,请使用简单的索引mystorage[counter]*(mystorage+counter)