簡體   English   中英

qsort不排序unsigned long int列表

[英]qsort not sorting list of unsigned long ints

在嘗試排序一系列無符號長整數時,以下代碼會產生奇怪的結果。 我不知道為什么。 它編譯無警。 問題出在我使用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);
}
*(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)]

應該清楚的是,這兩個將訪問數組邊界之外。

您的程序在該部分中是錯誤的

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)

暫無
暫無

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

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