gpt4 book ai didi

c - 解释 qsort 库中使用的函数的 typedef

转载 作者:行者123 更新时间:2023-12-04 09:16:25 24 4
gpt4 key购买 nike

我正在使用 qsort 库函数对结构元素数组进行排序,在互联网上搜索时我找到了一个资源:INFO: Sorting Structures with the C qsort() Function @支持.微软。

我知道 qsort 函数需要通过通用指针进行类型转换。

但是我无法得到这一行:

typedef int (*compfn) (const void*, const void*);

已声明的,及其后续调用:

qsort((void *) &array,              // Beginning address of array
10, // Number of elements in array
sizeof(struct animal), // Size of each element
(compfn)compare // Pointer to compare function
);
  1. typedef 的行为如何,我的意思是我们对 int (*compfn)int (compfn) 进行了哪些类型定义?
  2. 如果是前者,那么调用不应该是(*compfn)吗?

最佳答案

语法:

typedef  int (*compfn)  (const void*, const void*);
^ ^ ^ ^ ^
| return type | arguments type
| new type name
defining new type

compfn 是一个新的用户定义的 typetypedef 关键字定义,

因此,您已经使用我上面描述的语法将 int (*)(const void*, const void*); 准确地定义为 comfn

声明:

 compfn  fun; // same as: int (*fun)  (const void*, const void*);

表示fun 是一个函数指针,它接受两个const void* 类型的参数并返回int

假设你有一个像这样的函数:

int xyz  (const void*, const void*);    

然后您可以将xyz 地址分配给fun

fun = &xyz; 

在调用 qsort() 时:

在表达式 (compfn)compare 中,您正在将函数 compare 类型转换为 (compfn) 类型的函数。

一个疑问:

shouldn't the call be (*compfn).

不,它的类型名不是函数名。

注意:如果你只写 int (*compfn) (const void*, const void*); 而没有 typedef 那么 comfn 将是一个指向返回 int 并接受两个 const void*

类型参数的函数的指针

关于c - 解释 qsort 库中使用的函数的 typedef,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17782679/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com