0

How can I make an iterator over a dynamic array (in a struct)?

  • 1
    This is not C#, please check your tags – iakobski May 16 '19 at 19:28
  • cont_begin and cont_end are inconsistent with each other. one is returning the value of an element in a->array, the other is returning the address. – MFisherKDX May 16 '19 at 19:41
  • 1
    while it is UB to access outside the bounds of your array, it is legal to point 1 element past the bound. so `return a->array + a->size` is legal. See: https://stackoverflow.com/a/45335768/8767209 – MFisherKDX May 16 '19 at 19:46

1 Answers1

1

Your dynamic array, as represented by type struct _Lista, does not contain "elements of any type". At least not directly. It contains only and exactly elements of type void *. Pretty much everything you've written will work if you change type iterator accordingly, to a double pointer:

typedef void **iterator;

Do note, however, that this iterator implementation has a severe flaw: it does not carry any information about the bounds of the list. That may be OK if you ensure that there is a sentinel value after the last valid element (and maybe before the first, too), but otherwise you'll need a more complex data structure than just one pointer.

John Bollinger
  • 160,171
  • 8
  • 81
  • 157