Originally posted by: aCynic2
Originally posted by: HigherGround
Originally posted by: aCynic2
Originally posted by: HigherGround
nope, can't do that ... unless you Player **gamePlayers = new Player*[numPlayers];
That's how you allocate for the pointer to the pointers in a dynamic multi-dimensional array in C++?
what's with the question mark?
I should have rephrased:
Is that how you allocate for the pointers to pointers in a dynamic multi-dimensional array in C++?
I do it like this in C:
if ((mdl->surface_list = (SURFACE **)realloc ( mdl->surface_list, (mdl->num_surfaces * 2) * sizeof (SURFACE *))) == NULL)
{
// error handler here
}
I'm curious if the method you posted is the proper way in C++.
I think as my first C++ project, I'm going to port fisix over from non-OOP C to OOP C++. Fisix being the 3D object tracer that generates physical data.
I think it's more OO when compared to going through a series of mallocs/sizeofs/explicit casts. A lot of people stick to reallocs because it's so much cooler to fall back on old school one liners instead of going with the check if need to realloc, alloc temp array, copy contents, delete old array, assignment. However C++ gives you ability to skip all that with template classes. For example here's a simple mem class along with the dynarray class, which does the reallocs for you.
template <typename T>
class Memory {
public:
static T* alloc(int size) {
static int s = 0;
return realloc(NULL, s, size);
}
static T* realloc(T* t, int& current_size, int new_size) {
T* result = new T[new_size];
if(result != NULL) {
if(t != NULL && current_size > 0) {
for(int j =0; j<current_size; j++) {
result[j] = t[j];
}
delete [] t;
}
current_size = new_size;
}
else {
current_size = 0;
}
return result;
}
};
template <typename T>
class Array {
private:
T* _array;
int _position;
int _size;
void grow(int factor = 2) {
_array = Memory<T>::realloc(_array, _size, _size * factor);
}
bool at_limit() {
return _position == _size - 1;
}
public:
Array(int size) {
_array = Memory<T>::alloc(size);
_size = size;
_position = 0;
}
virtual ~Array() {
for(int j = 0; j < _position; j++)
delete _array[j];
delete [] _array;
}
void append(T t) {
if(at_limit())
grow();
_array[_position++] = t;
}
};
int main() {
Array<A*> array(10);
for(int j = 0; j < 21; j++)
array.append(new A());
return 0;
}
EDIT: is 'attach code' function completely broken, or is it just me?