You need to enable JavaScript to run this app. C语言如何存储结构体指针转换结果以简化代码并理解相关语法
优惠活动
大模型
产品
解决方案
定价
更多

C语言如何存储结构体指针转换结果以简化代码并理解相关语法

正确的转换结果存储写法

你需要用const struct listing*类型的指针变量存储转换结果,注意原输入参数是const void*,需要保留const限定符避免编译警告,优化后的完整函数如下:

int price_comparator(const void* p, const void *q){
    const struct listing *list_p = p;
    const struct listing *list_q = q;

    float price1 = list_p->price;
    float price2 = list_q->price;

    return (price1 - price2);
}

C语言允许void*类型指针直接赋值给其他类型的指针变量,不需要额外强转,如果你需要兼容C++标准可以显式强转:const struct listing *list_p = (const struct listing*)p;

错误写法原因

  • struct structOne = ((listing*)p); 存在两处错误:一是C语言中结构体完整类型名为struct listing,不能直接写listing作为类型,也不能用struct structOne自定义未声明的结构体类型;二是你将指针类型的值赋值给了结构体变量,类型不匹配。
  • void structOne = ((listing*)p); 错误:void是无类型标记,不能用来定义普通变量,仅可用来定义无类型指针void*。

原表达式括号用法解释

((struct listing*)q)->price 中的括号是运算符优先级要求:
类型转换运算符的优先级低于->成员访问运算符,如果去掉内层括号,表达式会被错误解析为struct (listing* q)->price,不符合语法规则。内层括号的作用是先将q转换为struct listing*类型,再访问成员。外层括号仅为可读性添加,可以省略。

无箭头运算符的等价写法

a->b是(*a).b的语法糖,所以你可以用解引用+.成员访问的写法实现等价逻辑,无需箭头运算符:

float price1 = (*(const struct listing*)p).price;
float price2 = (*(const struct listing*)q).price;

注意此处的括号同样不能省略:解引用运算符*优先级低于.成员访问运算符,不加括号会优先计算(const struct listing*)p.price,出现语法错误。


内容的提问来源于stack exchange,提问作者john horton

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.11 18:18:03