Hi,
I’m a C programmer who recently started to learn Zig. I defined a base struct NodeBase
and its child struct NodeInternal
as follow:
const std = @import("std");
const Allocator = std.mem.Allocator;
const NodeKind = enum {
Internal,
Leaf,
};
const NodeBase = struct {
kind: NodeKind,
pub fn init(kind: NodeKind) NodeBase {
return .{
.kind = kind,
};
}
};
const NodeLeaf = struct {
base: NodeBase,
child: *NodeBase,
pub fn create(allocator: Allocator) !*NodeLeaf {
var n = try allocator.create(NodeLeaf);
n.base = NodeBase.init(NodeKind.Leaf);
n.child = undefined;
return n;
}
};
And wanted to access a field (kind
) of the base struct in the NodeInternal by casting a pointer type as follow:
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
const allocator = gpa.allocator();
const leaf_n = try NodeLeaf.create(allocator);
const base_n: *NodeBase = @ptrCast(leaf_n);
std.debug.print("align-of\t: leaf_n {d}, base_n {d}\n", .{ @alignOf(NodeLeaf), @alignOf(NodeBase) });
std.debug.print("pointer\t\t: leaf_n {*}, base_n {*}\n", .{ leaf_n, base_n });
std.debug.print("kind\t\t: leaf_n {any} base_n {any}\n", .{ leaf_n.base.kind, base_n.kind });
std.debug.print("ptr of kind\t: leaf_n {*} base_n {*}\n", .{ &(leaf_n.base.kind), &(base_n.kind) });
}
However, I got the different addresses with/without a pointer casting; the last output shows different addresses for the same field:
align-of : leaf_n 8, base_n 1
pointer : leaf_n main.NodeLeaf@104818000, base_n main.NodeBase@104818000
kind : leaf_n main.NodeKind.Leaf base_n main.NodeKind.Internal
ptr of kind : leaf_n main.NodeKind@104818008 base_n main.NodeKind@104818000
How can I get the correct address of kind
even after a pointer casting?