You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Zig排序结构体数组报错:expected error union type, found 'void'

Zig结构体数组排序问题:编译器错误与段故障解决

编译器错误:expected error union type, found 'void'

std.sort.sort函数的返回类型是void,它不会返回错误联合类型,因此不需要用try关键字捕获错误。直接移除try前缀即可解决这个编译错误。

段错误:Segmentation fault at address 0x0

出现空地址访问的段错误,大概率是以下原因之一:

  • 原始数组arr无效:比如arr.ptr为0x0、arr.len是非法值,导致分配新数组array时长度错误,或复制元素时访问非法内存。
  • 未正确填充新数组:只分配了内存但未将arr的元素复制到array中,或手动赋值时逻辑出错。

修复步骤:

  1. 确保arr是有效的slice,包含合法的长度和元素。
  2. 使用std.mem.copy安全复制元素到新数组,避免手动赋值出错:
    std.mem.copy(Node, array, arr);
    
  3. 确认排序逻辑:你的cmp函数会让数组按data字段降序排列,若需要升序,将判断条件改为a.data < b.data。

完整可运行示例代码

const std = @import("std");

const Node = struct {
    data: u32,
    value: ?u32,
};

fn cmp(context: void, a: Node, b: Node) bool {
    _ = context;
    // 降序排列,改为 a.data < b.data 可实现升序
    return a.data > b.data;
}

pub fn main() !void {
    var general_purpose_allocator = std.heap.GeneralPurposeAllocator(.{}){};
    defer std.debug.assert(!general_purpose_allocator.deinit());
    const gpa = general_purpose_allocator.allocator();

    // 示例原始数组
    const arr = [_]Node{
        .{.data = 3, .value = 10},
        .{.data = 1, .value = 20},
        .{.data = 2, .value = null},
    };

    var array: []Node = try gpa.alloc(Node, arr.len);
    defer gpa.free(array);

    // 安全复制元素
    std.mem.copy(Node, array, &arr);

    // 正确调用排序函数(无try)
    std.sort.sort(Node, array, {}, cmp);

    // 验证排序结果
    for (array) |node| {
        std.debug.print("data: {}, value: {?}\n", .{node.data, node.value});
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 19:42:35