我正在用C编写一个模拟器。它的内存是字节可寻址的,所以我使用的是char数组,但我需要读/写未对齐的32位整数。
目前我正在使用*((unsigned int*) &memory[address])
,但它看起来非常可怕。最好的方法是什么?
答案 0 :(得分:4)
您可以直接使用memcpy()
。例如:
unsigned int x = 10;
unsigned char* memory = malloc(sizeof(unsigned char) * 512);
address = sizeof(unsigned char) * 256;
memcpy(memory + address, &x, sizeof(unsigned int));