简体   繁体   English

stdlib qsort比较功能中的类型转换

[英]type conversion in comparison function of stdlib qsort

This code snippet is mainly from man page of qsort. 此代码段主要来自qsort的手册页。

int cmp(const void *p1, const void *p2)
{
   char s1 = *(*(char * const *)p1);
   char s2 = *(*(char * const *)p2);
   return s1 - s2;
}

int main(int argc, char *argv[])
{
  int j; 
  printf("Before Qsort: \n");
  for(j = 1; j <argc ; j++)
    printf("%s ", argv[j]);
  printf("\n");
  qsort(&argv[1], argc - 1, sizeof(char *), cmp);
  printf("After Qsort: \n");
  for(j = 1; j <argc ; j++)
    printf("%s ", argv[j]);
  printf("\n");
}

I can understand I pass the address of pointer to char array which is &argv[1] in the qsort However, I am confused why I have to do the following cast to get the value? 我可以理解,我将指针的地址传递给了qsort中的&argv [1]的char数组。但是,我很困惑为什么我必须执行以下强制转换来获取值?

*(*(char * const *)p1)

I also checked other questions in stackoverflow, it is easy when we pass 1-D array. 我还检查了stackoverflow中的其他问题,当我们传递一维数组时很容易。 So, I can use 所以,我可以使用

type var = *(const type *)p1 to get the value 输入var = *((const type *)p1以获取值

Looking into this example, the type cast looks so weird to understand. 看这个例子,类型转换看起来太奇怪了。

Would you please help me to understand the meaning of every piece cast to reach the final value? 您能否帮助我理解每一个达到最终价值的作品的意义?

Thanks. 谢谢。

This: 这个:

char s1 = *(*(char * const *)p1);

Does two things: 做两件事:

  • Dereference (char * const *) p1 , ie cast p1 to a pointer to a character pointer (let's ignore the const , and dereference that. That yields a character pointer. 取消引用(char * const *) p1 ,即将p1转换为指向字符指针的指针(让我们忽略const ,并取消引用。这产生了一个字符指针。
  • Dereference that character pointer, yielding a single character. 解引用该字符指针,产生一个字符。

The code for s2 is of course the same, but for p2 . s2的代码当然是相同的,但是p2

The qsort() library function will call cmp() with p1 and p2 pointing into argv , which is not a "2D char array", it's a 1D array of character pointers. qsort()库函数将调用cmp()其中p1p2指向argv ,这不是“ 2D char数组”,它是字符指针的1D数组。 So qsort() will call cmp() with pointers pointing at those pointers, since it's the pointers that are being sorted. 所以qsort()将使用指向这些指针的指针来调用cmp() ,因为正是这些指针被排序了。

The sorting is then (dangerously) done by subtracting only these first characters from each other. 然后(危险地)通过仅相互减去这些第一个字符来完成排序。 That part, the return, is better written: 最好把这部分写成:

return s1 < s2 ? -1 : s1 > s2;

As posted the code has integer underflow issues. 如发布的代码有整数下溢问题。

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

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