Writing an int to a char array
I'm writing an emulator in C. Its mem开发者_开发百科ory is byte-addressible so I'm using a char array, but I need to read/write unaligned 32-bit integers.
Currently I'm using *((unsigned int*) &memory[address])
, but it seems pretty horrible. What's the best way to do it?
You can use memcpy()
directly. For example:
unsigned int x = 10;
unsigned char* memory = malloc(sizeof(unsigned char) * 512);
address = sizeof(unsigned char) * 256;
memcpy(memory + address, &x, sizeof(unsigned int));
精彩评论