I’m trying to write an init()
function for PackedThing1
which passes back an instance where all struct variables are set to 0xFF (or at least all bits on for the type).
Can anyone explain why init2()
doesn’t do this. I’m sure I’ve misunderstood something.
init1()
creates a PackedThing1
with default values which is copied on the return, it gets printed as I’d expect.
init2()
creates an undefined
PackedThing1
which it then tries to @memset()
to 0xFF, but I get garbage back.
const std = @import("std");
pub const PackedThing2 = packed struct {
a: u4 = 0xA,
b: u4 = 0xB,
c: u4 = 0xC,
d: u4 = 0xD,
};
pub const PackedThing1 = packed struct {
const Self = @This();
a:u32 = 123,
b:u32 = 456,
c:PackedThing2,
pub fn init1() Self {
// pass back a PackedThing1 with default values
const r:Self = .{.c = .{}};
return r;
}
pub fn init2() Self {
var r:Self = undefined;
// pass back a PackedThing1 with 0xFF values???
@memset(std.mem.asBytes(&r), 0xFF);
return r;
}
};
pub fn main() !void {
var thing = PackedThing1.init1();
std.debug.print("thing={any}\n", .{thing});
var bytes = std.mem.asBytes(&thing);
std.debug.print("len={d} {X}\n", .{bytes.len, bytes});
thing = PackedThing1.init2();
std.debug.print("thing={any}\n", .{thing});
bytes = std.mem.asBytes(&thing);
std.debug.print("len={d} {X}\n", .{bytes.len, bytes});
}
For the second set of printing, I get len=16 { FF, FF, FF, FF, FF, FF, FF, FF, FF, FF, 0, 0, 0, 0, 0, 0 }