-
memcpy problem
I am trying to create a function to add a new entry to an array of pointers, for example:
Assuming i have my CameraCircuit structure set like this:
Code:
struct CameraCircuit
{
GLdouble **locations_list;
GLint locations_list_size;
};
And it is already initialized so that i have:
cameras.locations_list = { {1,2,3}, {4,5,6}}
cameras.locations_list_size = 2;
And then i want to add a new camera, to the end of the list so that its location is:
{10,11,12}
My function should change the variable (redimensionate the memory etc...) so that after i call the function i have:
cameras.locations_list = { {1,2,3}, {4,5,6},{10,11,12}}
cameras.locations_list_size = 3;
I have this, the problem is that although it seems to set up the memory correctly, it doesent seem to copy the date at all.
The idea behind this is to create a buffer with the new size, copy the old data to it, then delete the old data and set the pointer to the new data. It may be quite simple, but i really have no idea how to do it. A little help would be greatlly apreciated. Thanks.
Code:
void CreateCamera(CameraCircuit *cameras, const double *location)
{
int locationsize = sizeof(double) * 3;
int oldsize = cameras->locations_list_size;
cameras->locations_list_size++;
int newsize = cameras->locations_list_size;
double **newbuffer = new double*[newsize];
for(int i = 0; i < newsize; i++)
newbuffer[i] = new double[3];
memset(newbuffer, 0, locationsize * newsize);
memcpy(newbuffer, cameras->locations_list, locationsize * oldsize);
for(int i = 0; i < oldsize; i++)
delete [] cameras->locations_list[i];
delete [] cameras->locations_list;
cameras->locations_list = newbuffer;
for(int i = 0; i < 3; i++)
cameras->locations_list[cameras->locations_list_size - 1][i] = location[i];*/
}
-
The problem is that you're using memcpy() as if you had a two dimensional array when what you really have is an array of pointers to arrays.
You'll have to loop through your array and copy them over manually. Or (and this is the better option), just copy the pointers over.
Here is the modified code:
Code:
void CreateCamera(CameraCircuit *cameras, const double *location)
{
int oldsize = cameras->locations_list_size;
cameras->locations_list_size++;
int newsize = cameras->locations_list_size;
double **newbuffer = new double*[newsize];
// no need to delete and reallocate each location-- just copy
// the pointers over
for(int i = 0; i < oldsize; i++)
newbuffer[i] = cameras->locations_list[i];
delete [] cameras->locations_list;
cameras->locations_list = newbuffer;
// add the new location to the end of the new array
newbuffer[newsize-1] = new double[3];
for(int i = 0; i < 3; i++)
cameras->locations_list[newsize - 1][i] = location[i];*/
}
Hope that helps.
-tf
-