Working version with variable-sized arrays
Added smarter realloc code