How to initialize an atomic ptr array

Quick question ā€¦ on array initialization

What do I need to do to initialize the array to null?

  const SomeStruct = struct {
      a: u32 = 42,
      b: usize,
  };

  var atomic_array: [2]std.atomic.Value(?*SomeStruct) = // HERE

  // -- to get the same as this
  // atomic_array[0].store(null, .monotonic);
  // atomic_array[1].store(null, .monotonic);

  const ptr = atomic_array[0].load(.monotonic);

  std.debug.print("{?}\n", .{ptr}); 
  // Should print 'null'

If I put undefined it does compile but crashes with
main.main.SomeStruct{ .a = General protection exception (no address available)

Also how would you do it if it was a Struct and not a Struct ptr?
I know there is mem.zeros that might work but Iā€™m unsure the proper way.

Also this will be a global static type variable without an initializer method.

Thanks!

Using array literal syntax with the ** operator, you can call a function to initialize the items:

const AtomicOptional = std.atomic.Value(?*SomeStruct);
var atomic_array = [_]AtomicOptional{AtomicOptional.init(null)} ** 2;
5 Likes