Hello,
I was expecting @alignOf(*anyopaque)
to return 1, but tried it with zig 0.14.0 on my machine and got 8.
const std = @import("std");
pub fn main() !void {
std.debug.print("@alignOf(*anyopaque) == {d}", .{@alignOf(*anyopaque)});
}
I was expecting 1 because from my understanding:
- If
T
is a type then, by default, @alignOf(T) == @alignOf(*T)
@alignOf(anyopaque) == 1
- If an anyopaque pointer can point to any type, then it makes sense for it to have an alignment of 1
- if you try to
@ptrCast
a *anyopaque
you (can) get an error with a note saying " ‘*anyopaque’ has alignment ‘1’ "
This isn’t correct.
comptime {
@compileLog(@alignOf(u8), @alignOf(*u8));
}
Compile Log Output:
@as(comptime_int, 1), @as(comptime_int, 8)
4 Likes
I’m going to assume you understand where alignment comes from and just answer:
a pointer has the same size as usize
which varies by architecture, on x86_64 it’s 8 bytes. So it has an alignment of 8
2 Likes
Oh, I think I understand why I got confused:
For some reason, I thought @alignOf(*T)
was the same as @typeInfo(*T).pointer.alignment
.
But the latter returns the alignment of T
, not *T
, right?
Now it makes sense, pointers are aligned like usize, anyopaque represents an unknown type with unknown size, so its alignment is 1.
I wasn’t thinking straight, alright, thank you!