如何将结构拆分为块,以便将字节保存到 C/C++ 中的另一个数据结构
How to split a struct into chunks in order to save the bytes to another data structure in C/C++?
我正在尝试将大小为 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.
相关文章:
- 链表,反向函数,数据结构
- 如何使用set实现无序数据结构?
- 我们可以将数据永久保存为数据结构吗?
- C++中的可变长度数组/数据结构
- 用于存储由空格分隔的字符串的 C++/C 数据结构
- 通过 NIF 从C++返回自定义数据结构
- 编译器上的策略数据结构不起作用
- 尝试构建"lock-free"数据结构C++
- 设计将引用元素移动到开头的数据结构.C++
- 在学习数据结构之前对STL有一个了解是好的吗?
- 如何解析表示树状数据结构的字符串
- 我对数据结构、双向链表有一些问题
- googletest:测试太大的数据结构
- C++中deque数据结构的大O是什么?
- 我可以使用哪种数据结构来处理这种方式
- 将文本文件解析为树状数据结构
- C++ 中具有 O(1) 搜索时间复杂度的数据结构
- 哪些存储了不完整类型的 STL 数据结构可以用作类成员?
- C++,您能否设计一种数据结构,将指针保存在连续内存中并且不会使它们失效?
- 带参数的数据结构的全局声明