Hello, I have my code for a selection sort in Zig attached below.
const std = @import("std");
pub extern fn scanf(noalias [*c]const u8, ...) c_int;
const print = std.debug.print;
pub fn main() !void {
var arr = [_]u8{ 0, 0, 0, 0, 0, 0 };
// Prompt the user to enter 6 values
print("Please enter 6 values.\n", .{});
// Read the values from the user
_ = scanf("%d %d %d %d %d %d", &arr[0], &arr[1], &arr[2], &arr[3], &arr[4], &arr[5]);
// Sort the values using the selection sort algorithm
// var sorted_arr = arr;
// _ = sorted_arr;
// sortVal(&sorted_arr);
sortVal(&arr);
// Copy the sorted values back to the original array
// var i: u8 = 0;
// for (sorted_arr) |elem| {
// arr[i] = elem;
// i += 1;
// }
// Print the sorted values
print("The sorted values are: {}, {}, {}, {}, {}, {}\n", .{ arr[0], arr[1], arr[2], arr[3], arr[4], arr[5] });
}
// Sorts an array of 6 unsigned 8-bit integers in ascending order
pub fn sortVal(arr_sort: *[6]u8) void {
const n: u8 = 6;
var min_idx: u8 = 0;
var temp: u8 = 0;
var i: u8 = 0;
while (n - 1 > i) : (i += 1) {
min_idx = i;
var j: u8 = i + 1;
// Find the index of the minimum element in the unsorted portion of the array
while (n > j) : (j += 1) {
if (arr_sort[j] < arr_sort[min_idx]) {
min_idx = j;
}
}
// Swap the minimum element with the first element in the unsorted portion of the array
temp = arr_sort[min_idx];
arr_sort[min_idx] = arr_sort[i];
arr_sort[i] = temp;
}
}
Running this gives me the following output:
$ zig run sorting_mess.zig
Please enter 6 values.
1 2 3 4 8 6
The sorted values are: 1, 2, 3, 4, 6, 8
[1] 33396 abort zig run sorting_mess.zig
This doesn't happen when I copy the array to modify it. Why? Not thread safe? Is it a memory safety thing? I'm a beginner


huh