简体   繁体   English

带有指向空指针的qsort

[英]qsort with pointer to pointer to void

qsort is working here, but if each member of array v occupies sizeof(void *) , why is qsort expecting sizeof(int) ? qsort在这里工作,但是如果数组v每个成员都占用sizeof(void *) ,为什么qsort期望sizeof(int)

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

int comp(const void *pa, const void *pb)
{
    int a = *(int *)pa;
    int b = *(int *)pb;

    if (a > b)
        return +1;
    else
    if (b > a)
        return -1;
    else
        return 0;
}

int main(void)
{
    int i, a[] = {3, 1, 2, 0, 4};
    void **v;

    v = malloc(sizeof(void *) * 5);
    for (i = 0; i < 5; i++) {
        v[i] = &a[i];
    }
    for (i = 0; i < 5; i++) {
        printf("%d\n", *(int *)v[i]);
    }
    qsort(v[0], 5, sizeof(int), comp); // why sizeof(int) if v is void **
    printf("Sorted:\n");
    for (i = 0; i < 5; i++) {
        printf("%d\n", *(int *)v[i]);
    }
    free(v);
    return 0;
}
qsort(v[0], 5, sizeof(int), comp); // why sizeof(int) if v is void **

The address of the start of the memory block to be sorted that you pass to qsort is 您传递给qsort要排序的内存块的开始地址是

v[0] = &a[0]

the address of the initial element of a , so the array that you sort is a , not the block whose initial element v points to. 的初始元素的地址a ,这样就排序是阵列a ,而不是它的初始元件块v点。 a 's elements are int s, so sizeof(int) is the correct size. a的元素是int ,因此sizeof(int)是正确的大小。

If you want to sort the array of pointers, you need to pass the address of the first element in that array, &v[0] , or simply v to qsort . 如果要对指针数组进行排序,则需要将数组中的第一个元素的地址&v[0]或简单地v传递给qsort Then of course the size argument must be sizeof (void*) : 然后当然,size参数必须是sizeof (void*)

qsort(v, 5, sizeof(void*), cmp);

but for that, you can't use the comparison function you have, you need 但是为此,您不能使用已有的比较功能,需要

int cmp(const void *pa, const void *pb) {
    int a = *(int*)(*(void**)pa);
    int b = *(int*)(*(void**)pb);

    if (a > b)
        return +1;
    else
    if (b > a)
        return -1;
    else
        return 0;
}

or something similar. 或类似的东西。 Since what is passed to the comparison function from qsort is the address of the things to compare, we need one indirection to get the pointers to compare, and since here we want to compare pointers by what int values they point to, we need the second indirection to get the pointed-to int s. 由于从qsort传递到比较函数的是要比较的对象的地址,因此我们需要一种间接方式来获取要比较的指针,并且由于这里我们要根据指针所指向的int值来比较指针,因此我们需要第二种间接获取指向的int

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

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