为结构数组分配内存块

bit*_*ise 2 c++

我需要在一个坚实的内存块中分配这个结构的数组."char*extension"和"char*type"的长度在编译时是未知的.

struct MIMETYPE
{
 char *extension;
 char *type;
};
Run Code Online (Sandbox Code Playgroud)

如果我使用"new"运算符来自己初始化每个元素,则内存可能会分散.这就是我尝试为它分配一个连续的内存块的方法:

//numTypes = total elements of array
//maxExtension and maxType are the needed lengths for the (char*) in the struct
//std::string ext, type;
unsigned int size = (maxExtension+1 + maxType+1) * numTypes;
mimeTypes = (MIMETYPE*)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, size);
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试像这样加载数据时,当我稍后尝试访问数据时,数据全部乱序并且分散.

for(unsigned int i = 0; i < numTypes; i++)
{
 //get data from file
 getline(fin, line);
 stringstream parser.str(line);
 parser >> ext >> type;

 //point the pointers at a spot in the memory that I allocated
 mimeTypes[i].extension = (char*)(&mimeTypes[i]);
 mimeTypes[i].type = (char*)((&mimeTypes[i]) + maxExtension);

 //copy the data into the elements
 strcpy(mimeTypes[i].extension, ext.c_str());
 strcpy(mimeTypes[i].type, type.c_str());
}
Run Code Online (Sandbox Code Playgroud)

谁能帮我吗?

编辑:

unsigned int size = (maxExtension+1 + maxType+1);
mimeTypes = (MIMETYPE*)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, size * numTypes);

for(unsigned int i = 0; i < numTypes; i++)
    strcpy((char*)(mimeTypes + (i*size)), ext.c_str());
    strcpy((char*)(mimeTypes + (i*size) + (maxExtension+1)), type.c_str());
Run Code Online (Sandbox Code Playgroud)

Dew*_*wfy 5

你混合2分配:

1)管理MIMETYPE和

2)管理字符数组

可能(我真的不明白你的目标):

struct MIMETYPE
{
    char extension[const_ofmaxExtension];
    char type[maxType];
};
Run Code Online (Sandbox Code Playgroud)

最好在表单中分配线性项:

new MIMETYPE[numTypes];
Run Code Online (Sandbox Code Playgroud)