student@ubuntu:~$
c 5/5 50 XP

Generic Containers

0%

Quick Reference

Generic container ingredients:

typedef struct {
    void *data;          // Raw byte buffer
    size_t elem_size;    // Bytes per element
    int count;           // Current elements
    int capacity;        // Total capacity
    int (*compare)(const void *, const void *);  // Comparator
    void (*free_fn)(void *);                     // Element destructor
} GenericArray;

Accessing element i:

void *elem = (char *)arr->data + i * arr->elem_size;

Copying an element in:

memcpy((char *)arr->data + arr->count * arr->elem_size,
       new_elem, arr->elem_size);

Common Pitfalls

  • Forgetting elem_size – Without it, you can’t navigate the buffer. Every operation needs it.
  • void * arithmetic – Not standard C. Cast to char * for byte-level arithmetic.
  • Type mismatch – Storing ints but reading as doubles. No compiler help — you must be disciplined.
  • Shallow copymemcpy copies bytes. If elements contain pointers, you get shared references.

Unlocks

Complete this skill to see what it unlocks.