jeudi 2 mars 2017

dynamic array size within struct without another member indicate the size

I have a struct defined as:

struct Voxel1
{
   float array[16];
};

where later I can allocate an image as a continuous memory of a specified number of Voxels, e.g.,

int voxelNum = 1000;
Voxel1* image = (Voxel1*)calloc(voxelNum, sizeof(Voxel1));

then I can access continuous memory of sizeof(Voxel1) to do some operation, e.g.,

Voxel1 a;
//do some computation on a, 
//copy it to the 101-th voxel in the image
image[100] = a;

My problem is that later I decide the size of array is decided at run-time, i.e., the array member in Voxel1 is of dynamic size. Is there a way that I can do it? My requirement is that I don't want to save an additional member to indicate the size of the array, like the one below:

struct Voxel2
{
   size_t size;
   float* array;
}IDontWantThisDefinition;

Due to this additional member, later my actual voxel2 size will be sizeof(float)*size+sizeof(size_t) , now when I try to modify voxel values, they are not as continuous as before.

What I desire is some definition (I know Voxel3 is invalid) has the following definition except size can be decided at run-time:

struct Voxel3
{
   //so I want size to be static so that it does not take memory on the stack
   //also I want it to be const so that it can be used to define array's size
   static const size_t size;
   float array[size];
}InvalidDefinition;

where in a program I can do something like this:

int main(int argc, char** argv)
{
    int arraysize = 32;
    //allocate 1000 voxels where each voxel has 32 float element
    Voxel3* image = (Voxel3*)calloc(1000, sizeof(Voxel3));
    Voxel3 anotherVoxel;
    image[100]=anotherVoxel;
}

I am not sure if there is any solution to satisfy such design, or what design can do something close to what I want. Thanks in advance.

Aucun commentaire:

Enregistrer un commentaire