Hasty Briefsbeta

Bilingual

A generic dynamic array in C that stores no capacity and needs no struct

5 hours ago
  • #C Programming
  • #Dynamic Arrays
  • #Memory Management
  • Uses a generic dynamic array in C via an array of two pointers: first pointer stores length, second pointer points to data.
  • Example structures: int *vec[2] = { 0 }; for ints, struct person *people[2] = { 0 }; for structs.
  • Length is accessed via (uintptr_t)vec[0], and data via vec[1].
  • The vec_push macro adds a value to the end and returns true if successful.
  • No structs are needed (e.g., no IntVec), but relies on implementation-defined behavior for storing length as uintptr_t in a pointer.
  • Capacity is not stored; computed when length is zero or a power of two, calling realloc for the next power of two.
  • Drawback: Manual capacity reservations are ineffective as realloc triggers when length hits a power of two.