#Are pointer that are created in loops not reinitialized in each run?

1 messages · Page 1 of 1 (latest)

bright garnet
#

I'm relatively new to zig and playing around with advent of code right now.
I have a loop in which i am reading two point's per line and putting them in a list or not depending on whether they are already there, but at the end of all the lines all my points have the contents of the last line.

var points = std.ArrayList(*Point).init(allocator);
while (it.next()) |line| {
  var pointA: *Point = undefined;
  var pointB: *Point = undefined;
  
  if (aExists == false) {
    var point = Point{
     .name = a,
    };
    pointA = &point;
    try points.append(pointA);
  }
  if (bExists == false) {
    var point = Point{
      .name = b,
    };
    pointB = &point;
    try points.append(pointB);
  }
}

This code is obviously abridged, but i hope the issue is clear.

twilit pebble
#

&point is a pointer to stack memory, the pointer dies (or is freed) the moment point goes out of scope, which happens at the end of every loop iteration; the compiler is smart, so the space used by point is reused on every loop iteration and you're essentially just appending the same pointer over and over

bright garnet
#

Thanks that does make sense, but how could I create this list of Points in a way that I don’t lose them?

twilit pebble
#

the easiest would be having an ArrayList(Point), otherwise you'll have to use an allocator to create a copy

bright garnet
#

Creating it on the heap with an allocator worked great. Again thanks for the help.

stone pagoda
#

I will note that copying the struct is generally better than allocating, because allocations want freeing - and that's strictly more involved than just copying the thing into the arraylist.

#

Indeed, I would generally suggest storing things by-value instead of by-pointer unless you have a good reason to do so.

boreal saddle
#

or if you do need it to be a handle, you can have a seperate arraylist of Points and this arraylist could contain indexes into that array

#

but yeah I dont see why youd want it to store a pointer