Namaran

Code daily. Without assist.

2026-11-15

swap_words.zig

const std = @import("std");

pub fn main(init: std.process.Init) !void {
    var bytes: [8]u8 align(4) = .{ 1, 2, 3, 4, 5, 6, 7, 8 };
    const words: *[2]u32 = @ptrCast(&bytes);
    std.mem.swap(u32, &words[0], &words[1]);
    var buf: [256]u8 = undefined;
    var stdout_writer = std.Io.File.stdout().writer(init.io, &buf);
    const stdout = &stdout_writer.interface;
    try stdout.print("{any}\n", .{bytes});
    try stdout.flush();
}

これは何を出力するでしょうか?

Answer

Output

{ 5, 6, 7, 8, 1, 2, 3, 4 }

@ptrCast はアドレスをそのままにして、ポインタの型だけを変えます。words は bytes と同じ8バイトを指しますが、要素は4バイトの u32 なので、words[0] は bytes の0から3バイト目、words[1] は4から7バイト目です。添字の1は、新しい型の要素1つぶんの4バイト先を指します。

std.mem.swap は2つの u32 の中身を丸ごと入れ替えるので、前半の4バイト 1, 2, 3, 4 と後半の4バイト 5, 6, 7, 8 がそのまま入れ替わります。4バイトの塊を、並びを保ったまま動かすだけなので、u32 の値がバイトをどの順で持つかは結果に関係しません。{any} は配列を { 5, 6, 7, 8, 1, 2, 3, 4 } の形で出力します。

&words[0] と &words[1] を bytes の0バイト目と1バイト目だと読むと、2バイトだけを入れ替えたと考えて { 2, 1, 3, 4, 5, 6, 7, 8 } と答えます。