Hello. I am writing a program with some dynamic arrays of pointers to objects (not arrays of objects). Since there will be A LOT of tacking on new objects to the arrays, for the purposes of efficiency, I am implementing an algorithm to fill up a buffer array first and only tack it on the end of the real array when the buffer reaches the same size as the real array.
The problem: the variables 'liv_s' and 'liv_tmp_s' (see code below) are not updated as they should be, causing to whole thing to mess up. I think 'liv_tmp_s' is the culprit, but I can't be certain. When I run the MSVC10 debugger, it seems to claim that the addresses of liv_s and liv_tmp_s are the same, and yet they have different values!?!?!
I still have some simplification to do, but here's the algorithm. ('Cell' is the class of objects I'm using. 'dest' is the array, 'buf' is the buffer array, 'dest_s': # of elem in dest, 'buf_s': # of elem in buf, cell: pointer to add, 'ret_dest': pointer to the array pointer, 'ret_buf': pointer to the buffer array pointer.)
void add_to_array(Cell **dest, Cell **buf, int *dest_s, int *buf_s, Cell *cell, Cell ***ret_dest, Cell ***ret_buf) {
if (*buf_s < *dest_s) { //if buffer is smaller than array
//add cell to buf
Cell **tmp = new Cell*[*buf_s + 1]; //new buffer array, 1 elem larger
int i;
for (i = 0; i < *buf_s; i++) {
tmp[i] = buf[i]; //copy old elems over
}
tmp[i] = cell; //add the new one
delete [] buf; //delete old buffer
*ret_buf = tmp; //replace the old pointer to the buffer with the new one
*buf_s++; //new size of the buffer <-- issue here?
} else {
//add buf and cell to dest
Cell **tmp = new Cell*[*dest_s + *buf_s + 1]; //new larger array
int i;
for(i = 0; i < *dest_s; i++) {
tmp[i] = dest[i]; //copy old data over
}
for (i; i < *buf_s + *dest_s; i++) {
tmp[i] = buf[i]; //add buffer's data
}
tmp[i] = cell; //add the new elem
delete [] dest; //delete old array
delete [] buf; //delete old buffer
*ret_dest = tmp; //replace old array pointer with new one
*dest_s += (*buf_s + 1); //new array size <-- issue here?
*ret_buf = new Cell*[0]; //empty buffer
*buf_s = 0; //new buffer size <-- issue here?
}
}
my abbreviated program:
Cell *newCell;
Cell **living, **living_tmp;
int liv_s, liv_tmp_s;
int main() {
liv_s = 0;
liv_tmp_s = 0;
living = new Cell*[0];
living_tmp = new Cell*[0];
//for various integer values of x, i, and y:
newCell = new Cell(x+i, y);
add_to_array(living, living_tmp, &liv_s, &liv_tmp_s, newCell, &living, &living_tmp);
//
}
So, pointers to liv_s and liv_tmp_s get passed into the function as *dest_s and *buf_s, but liv_s and liv_tmp_s don't seem to be updated properly when the function changes *dest_s or *buf_s.
Suggestions? Thanks.