Skip to content

A question about obtaining variable addresses #24163

Closed as not planned
Closed as not planned
@xingxingtie

Description

@xingxingtie

hello, I am very interested in the Zig language and am trying to master it, But I found an interesting phenomenon when I learned that function parameters may pass values or references.

Zig Version

0.15.0-dev.769+4d7980645

Test code

const std = @import("std");

const S = struct { val: u32 };
fn f(xa: *S, xb : S) void {
    std.debug.print("before change: {} {*} {*}\n", .{xb.val, &xb.val, &xa.val});
    xa.val = 20;
    std.debug.print("after change:  {} {*} {*}\n", .{xb.val, &xb.val, &xa.val});
}

pub fn main() void {
    var x: S = .{ .val = 0 };
    std.debug.print("in main: {} {*}\n", .{x.val, &x.val});
    f(&x, x);
}

#output:

in main: 0 u32@40835ff74c
before change: 0 u32@40835ff6dc u32@40835ff74c
after change:  20 u32@40835ff6dc u32@40835ff74c

#question:
Why do xa.val and xb.val have different addresses, but when I modify xa.val, the value of xb.val can be changed, Is there a problem with the way I get the address? Or some hidden magic that I don't know about?

Metadata

Metadata

Assignees

No one assigned

    Labels

    questionNo questions on the issue tracker, please.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions