Reputation: 331
I have a program that I've written that requires me to declare an array as such
float (*array)[3] = new float[faces * 3][3];
Now I understand the syntax and all, this is an array of pointers to fixed size arrays. What I don't understand is the underlying organization behind this. Since there was only one memory allocation (for the array of pointers) how does the memory for the fixed size arrays get allocated?
Along the same thread, since there was only one allocation there should be one deletion, meaning the array is deleted by
delete[] array;
but I'm confused as to how this gets all of the memory, given that it seems only the array of pointers has been deleted, as opposed to the memory they pointed to.
Upvotes: 0
Views: 216
Reputation: 7339
Baby steps.
First, these fixed-length arrays of float[3]
seem like special types. I'm guessing you'll be doing specific operations with them. You should wrap a float[3]
with the functions and operations that will work with them into a class. You may decide to use Vector<float>
internally and keep them at size 3, but std::vector
was designed to be appended to and removed from. I think there is another "std template" class that was designed for fixed-length multiples, but I don't know which. I don't use the STL much.
Once you've objectified your float[3]
's, however you do it, I think the rest will become easier as you start to see more clearly.
Upvotes: 0
Reputation: 21595
This is not an array of pointers to fixed size arrays. This is a pointer to a multidimensional array. Multidimensional arrays are implemented as one dimensional array, with some calculation upon accessing elements.
The memory layout is exactly like in this statement:
float *array = new float[(faces * 3) * 3];
or in this one (except faces
must be constant expression, and the allocation is now on the stack):
float arr3[faces*3][3];
float (*array)[3] = &arr3; // note the "&". it is not a decaying here
and this is a more familiar form of this pointer:
void something(float array[][3]); // this is not an array, but a pointer to one.
Note that the arrays of different sizes/dimensions are distinct types, and if you want to access a one dimensional array as a multi-dimensinal one, now will need to do the calculation of array[3][2]
yourself.
Upvotes: 1