繁体   English   中英

使用 qsort() 对数组进行排序

[英]Sorting an array using qsort()

我正在尝试检查两个数组是否包含相同的元素。 由于我不知道输入文件是否正确排序,我想先使用qsort()对数组进行排序,然后将其与数组cmpvalues进行比较。

但是我无法让qsort像数组cmpvalues那样对数组进行cmpvalues 存储值的数组应该像数组cmpvalues一样排序,以便更容易比较。

#include <stdio.h>

#define MAXCOLR   14
#define MAXLINE  100
#define MAXCHR  1024   
#define _GNU_SOURCE

typedef struct {
    char color[MAXCOLR];
    int value;
} colorval_t;

int cmpfunc(const void *a, const void *b) {
    int aa, bb;
    aa = *(int *)a;
    bb = *(int *)b; 
    return (aa - bb);   
}

int main(int argc, char **argv) {
    size_t n;
    int cmpvalues[] = {
        65,
         2,
         3,
         4,
         5,
         6,
         7,
         8,
         9,
        10,
        74,
        81,
        75,
        65,
         2,
         3,
         4,
         5,
         6,
         7,
         8,
         9,
        10,
        74,
        81,
        75
    };
    size_t ndx = 0;
    char buf[MAXCHR];
    colorval_t arr[MAXLINE] = {{ .color = "" }};

    FILE *fp = argc > 1 ? fopen(argv[1], "r") : stdin;

    if (!fp) { 
        perror("file open failed");
        return 1;
    }

    while (ndx < MAXLINE && fgets(buf, MAXCHR, fp)) {
        char c;
        if (sscanf(buf, "%13s %d", arr[ndx].color, &arr[ndx].value) == 2)
            ndx++;
        else if (sscanf(buf, "%13s %c", arr[ndx].color, &c) == 2) {
            arr[ndx].value = c;
            ndx++;
        }
    }
    if (fp != stdin)
        fclose(fp);   

    for (size_t i = 0; i < ndx; i++)
        printf("arr[%2zu] : %s %d\n", i, arr[i].color, arr[i].value);

    //sorts the array
    qsort(arr, 26, sizeof(arr[26]), cmpfunc);
    for (n = 0 ; n < 26; n++) {   
        printf("%d ", arr[n].value);
    }

    //checks if arrays have the same element
    int j;
    for (j = 0; j < 26; j++) {
        if (arr[j].value != cmpvalues[j]) {
            printf("wrong");
            break;
        }
    }
    return 0;
}

输入:

RED A
RED 2
RED 3
RED 4
RED 5
RED 6
RED 7
RED 8
RED 9
RED 10
RED J
RED Q
RED K
BLACK 10
BLACK J
BLACK Q
BLACK K
BLACK A
BLACK 2
BLACK 3
BLACK 4
BLACK 5
BLACK 6
BLACK 7
BLACK 8
BLACK 9

你的比较函数是错误的。

qsort函数将指针传递给您排序的数组中的元素,因此如果您有一个colorval_t数组,则参数的类型为colorval_t *

由于您将指针视为int *您不匹配,这将导致未定义的行为

这意味着你的比较函数应该看起来像

int cmpfunc (const void * a, const void * b) {
    colorval_t *first = (colorval_t *) a;
    colorval_t *second = (colorval_t *) b;

    return first->value - second->value;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM