Search code examples
zig

error: array literal requires address-of operator (&) to coerce to slice type '[]i8' in ZIG


I was trying to practice zig syntax by writing selection sort algorithm.

I haven't changed anything else after running zig init-exe except in src/main.zig

const std = @import("std");

fn selectionSort(arr: []i8) void {
    const n = arr.len;

    for (arr, 0..n - 1) |_, i| {
        var minIndex: usize = i;

        for (arr, i + 1..n) |_, j| {
            if (arr[j] < arr[minIndex]) {
                minIndex = j;
            }
        }

        if (minIndex != i) {
            // Swap arr[i] and arr[minIndex]
            var temp: i8 = arr[i];
            arr[i] = arr[minIndex];
            arr[minIndex] = temp;
        }
    }
}

pub fn main() void {
    var arr: []i8 = [_]i8{ 64, 25, 12, 22, 11 };

    std.debug.print("Original array: {}\n", .{arr});

    selectionSort(arr);

    std.debug.print("Sorted array: {}\n", .{arr});
}

I am getting the error src/main.zig:25:26: error: array literal requires address-of operator (&) to coerce to slice type '[]i8' var arr: []i8 = [_]i8{ 64, 25, 12, 22, 11 };

please tell me what's wrong

I tried running the code using zig build but I got the error mentioned above.

I was expecting the sorted array

[11,12,22,25,64]


Solution

  • As the compiler tells you, you have an incorrect cast of an array literal to a slice. Instead, use the literal and take the slice as needed, like this:

    var arr = [_]i8{ 64, 25, 12, 22, 11 };
    selectionSort(&arr);
    

    There are two more problems with this code:

    1. The format specifier {} wouldn't work for an array literal. Use {any}.
    2. The for loops would panic with "for loop over objects with non-equal lengths". Just remove arr from the loops, you don't use the values anyway.

    The fixed code looks like this:

    const std = @import("std");
    
    fn selectionSort(arr: []i8) void {
        const n = arr.len;
    
        for (0..n - 1) |i| {
            var minIndex = i;
    
            for (i + 1..n) |j| {
                if (arr[j] < arr[minIndex]) {
                    minIndex = j;
                }
            }
    
            if (minIndex != i) {
                var temp = arr[i];
                arr[i] = arr[minIndex];
                arr[minIndex] = temp;
            }
        }
    }
    
    pub fn main() void {
        var arr = [_]i8{ 64, 25, 12, 22, 11 };
    
        std.debug.print("Original array: {any}\n", .{arr});
    
        selectionSort(&arr);
    
        std.debug.print("Sorted array: {any}\n", .{arr});
    }
    

    And prints this:

    Original array: { 64, 25, 12, 22, 11 }
    Sorted array: { 11, 12, 22, 25, 64 }