3 ms·
Oh, the method I describe is more error prone than array of arrays, because if you ever modify the two variables you used to specify the array size, the compile
by Asooka 10y ago
Oh, the method I describe is more error prone than array of arrays, because if you ever modify the two variables you used to specify the array size, the compiler will just use the new values for array dimensions. If I had to do array of arrays though, I'd at least do something like
template<typename T>
T** make_2d_array(size_t m, size_t n) {
// TODO: add padding for alignment,
// but you're unlikely to need something aligned
// on a larger extent than sizeof(void*)
void *memory = malloc(m * sizeof(void*) + m * n * sizeof(T));
T** array = (T**)memory;
T* data = (T*)((char*)memory + m * sizeof(void*));
for (size_t i = 0; i < m; i++) {
array[i] = data + i * n;
}
return array;
}
And you can then delete the entire array with a single free().