在结构中使用Void*空格而不是malloc

Rio*_*Rio 1 c malloc c99

我目前有一个结构

typedef struct Entry {
    int counter;
    void *block;
} Entry;
Run Code Online (Sandbox Code Playgroud)

和一个mmap的内存块

void *memPtr = mmap(NULL, someSize*1024, PROT_READ|PROT_WRITE, 
                        MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
Run Code Online (Sandbox Code Playgroud)

然后我将条目一直添加到第一部分(这是愚蠢的,但那部分有点无关紧要),如下:

int AddEntry(void *data) {
   Entry entry;
   entry.counter = 1;
   entry.block = malloc(sizeof(char *) * SECTOR_SIZE);
   memcpy(entry.block, data, SECTOR_SIZE);
   memcpy(&memPtr[0], &entry, sizeof(Entry));
   return 0;
}
Run Code Online (Sandbox Code Playgroud)

这里的问题Entry是只有16个字节长,因为block是a void pointer.什么是保证该块最好的办法实际上的sizeof的大小(字符*)*SECTOR_SIZE和实际上有数据足够的空间,以及如何将一个加载data到entry.block?

谢谢!

And*_*mbe 5

如果我正确地阅读了这个问题,你就会问如何获得一个可以通过(较小的)访问的连续内存块 Entry *

最常见的方法是定义您的结构,如:

typedef struct Entry {
    int counter;
    unsigned char block[1];
}

int AddEntry(void *data) {
   Entry *entry;
   entry = malloc(sizeof(Entry) + ((SECTOR_SIZE-1) * sizeof(unsigned char));
   // obligitory NULL checks assumed here

// fill in structure entry->counter = 1; memcpy(entry->block, data, SECTOR_SIZE); memcpy(&memPtr[0], &entry, sizeof(Entry) + ((SECTOR_SIZE-1) * sizeof(unsigned char)); return 0; }

这也允许你访问第78个字节

typedef struct Entry {
    int counter;
    unsigned char block[1];
}
: block