我有一個結構定義爲:動態數組大小而不另一個構件指示大小
struct Voxel1
{
float array[16];
};
其中我可以在以後分配一個圖像作爲體素的一個特定數目的連續的存儲器,例如,
int voxelNum = 1000;
Voxel1* image = (Voxel1*)calloc(voxelNum, sizeof(Voxel1));
然後我可以訪問的sizeof(Voxel1)
連續內存做一些操作,例如,
Voxel1 a;
//do some computation on a,
//copy it to the 101-th voxel in the image
image[100] = a;
我的問題是後來我決定在運行時決定數組的大小,即Voxel1中的數組成員是動態大小的。有什麼方法可以做到嗎?我的要求是,我不希望保存額外的成員,以指示數組的大小,類似下面:
struct Voxel2
{
size_t size;
float* array;
}IDontWantThisDefinition;
由於這種額外的成員,後來我的實際voxel2規模將sizeof(float)*size+sizeof(size_t)
,現在當我嘗試修改體素值時,它們不像以前那樣連續。
我的願望是一些定義(我知道Voxel3無效)已除size
以下定義可以在運行時決定:
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];
}DesireButInvalidDefinition;
其中一個程序,我可以做這樣的事情:
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;
}
我不知道是否有任何解決方案來滿足這樣的設計,或者什麼設計可以做到接近我想要的東西。提前致謝。
你使用'c'還是'C++'?在你的用例中,它可以有所作爲。對於'c','Voxel2'看起來是最好的選擇。使'size'成爲一個全局/靜態的,定義_outside_ struct –
我將刪除C++標記,因爲它似乎是用C編碼的。 – juanchopanza