如何将结构拆分为块,以便将字节保存到 C/C++ 中的另一个数据结构

How to split a struct into chunks in order to save the bytes to another data structure in C/C++?

本文关键字:C++ 数据结构 另一个 保存 拆分 结构 字节      更新时间:2023-10-16

我正在尝试将大小为 1536 的结构拆分为三个大小相等的 512 字节块,以便可以将其保存到虚拟磁盘。虚拟磁盘的缓冲区大小限制为 512 字节。偏移指针时出现问题,但我不知道为什么。

这是SSCCE:

#include <iostream>
#include <string.h>
#include <stdlib.h>
#include <bitset>
#define SECTOR_SIZE  512
#define NUM_SECTORS  10000
typedef struct sector {
  char data[SECTOR_SIZE];
} Sector;
static Sector* disk;
struct dataBitmap {
    /* sizeof myBits = 1228 bytes */
    std::bitset<9795> myBits;
    /* 308 bytes not accounted for */
    char emptyData[308];
    /* dataBitmap will now perfectly overlay 3 sectors of disk */
} dataMap;
void Disk_Write(int sector, char* buffer)  {
    // quick error checks
    if((sector < 0) || (sector >= NUM_SECTORS) || (buffer == NULL)) {
        std::cout << "Error!";
    }
    // copy the memory for the user
    if((memcpy((void*)(disk + sector), (void*)buffer, sizeof(Sector))) == NULL) {
        std::cout << "Error!";;
    }
}
void Update_Bitmaps() {
    char * bytes = (char*) malloc(512);
    std::cout << "size of dataMap: " << sizeof(dataMap) << 'n';
    const void* a = &dataMap;
    const void* b = (const void*)((char*)a + 512);
    /* data bitmap is 3 times the size of regular sector */
    memcpy(&bytes, b, 512);
    //Disk_Write(2, (char *) bytes); /* offset for data bitmap is 2 */
    memcpy(&bytes, (char *) &dataMap + 512, 512);
    Disk_Write(2, (char *) bytes);
    //memcpy(&bytes, (char *) &dataMap.myBits + 1024, 512);
    //Disk_Write(2, (char *) bytes);
    free(bytes);
}
int main()
{
    Update_Bitmaps();
    return 0;
}

这是程序的输出:

size of dataMap: 1536
      0 [main] BitSet 8276 cygwin_exception::open_stackdumpfile: 
      Dumping stack trace to BitSet.exe.stackdump
Process returned 35584 (0x8B00)   execution time : 0.464 s

我意识到这是 C 风格的代码,但我不知道如何以这种方式复制字节。任何帮助,不胜感激。

您尚未为 disk 分配内存。

int main()
{
    disk = malloc(sizeof(*disk)*NUM_SECTORS); // Allocate memory for disk
    Update_Bitmaps();
    free(disk);           // Free the allocated memory.
    return 0;
}

此外,以下行不正确。

memcpy(&bytes, b, 512);
//Disk_Write(2, (char *) bytes); /* offset for data bitmap is 2 */
memcpy(&bytes, (char *) &dataMap + 512, 512);

他们需要

memcpy(bytes, b, 512);
//     ^^ just bytes, not &bytes.
//Disk_Write(2, (char *) bytes); /* offset for data bitmap is 2 */
memcpy(bytes, (char *) &dataMap + 512, 512);
//     ^^ just bytes, not &bytes.