From 6b31c86fea8d795a959c41b277e84be0ac4c1ea6 Mon Sep 17 00:00:00 2001 From: Felipe Pena Date: Sat, 8 Mar 2025 15:56:38 -0300 Subject: [PATCH] cgen: fix codegen for global array passed as mut (fix #23873) (#23881) --- vlib/v/gen/c/fn.v | 2 +- vlib/v/tests/global_init_array_test.v | 24 ++++++++++++++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) create mode 100644 vlib/v/tests/global_init_array_test.v diff --git a/vlib/v/gen/c/fn.v b/vlib/v/gen/c/fn.v index ca05d6efb1..f09aaf2c5d 100644 --- a/vlib/v/gen/c/fn.v +++ b/vlib/v/gen/c/fn.v @@ -2639,7 +2639,7 @@ fn (mut g Gen) ref_or_deref_arg(arg ast.CallArg, expected_type ast.Type, lang as && g.table.unaliased_type(arg_typ).is_pointer() && expected_type.is_pointer()) { if arg.is_mut { if exp_sym.kind == .array { - if (arg.expr is ast.Ident && arg.expr.kind == .variable) + if (arg.expr is ast.Ident && arg.expr.kind in [.global, .variable]) || arg.expr is ast.SelectorExpr { g.write('&') g.expr(arg.expr) diff --git a/vlib/v/tests/global_init_array_test.v b/vlib/v/tests/global_init_array_test.v new file mode 100644 index 0000000000..6a4bf8b8d3 --- /dev/null +++ b/vlib/v/tests/global_init_array_test.v @@ -0,0 +1,24 @@ +@[has_globals] +module main + +struct Rectangle { + x int + y int + w int + h int +} + +__global bricks = []Rectangle{} + +fn init_bricks(mut bricks []Rectangle) { + for i in 0 .. 5 { + bricks << Rectangle{i, 2 * i, 3 * i, 4 * i} + } + dump(bricks.len) +} + +fn test_main() { + assert bricks.len == 0 + init_bricks(mut bricks) + assert bricks.len == 5 +}