[英]How to read/write type values from “raw” memory in C?
How do I make something like this work? 我如何制作这样的作品呢?
void *memory = malloc(1000); //allocate a pool of memory
*(memory+10) = 1; //set an integer value at byte 10
int i = *(memory+10); //read an integer value from the 10th byte
Easy example: treat the memory as an array of unsigned char 简单示例:将内存视为unsigned char数组
void *memory = malloc(1000); //allocate a pool of memory
uint8_t *ptr = memory+10;
*ptr = 1 //set an integer value at byte 10
uint8_t i = *ptr; //read an integer value from the 10th byte
You can use integers too, but then you must pay attention about the amount of bytes you are setting at once. 您也可以使用整数,但是您必须注意一次设置的字节数。
The rules are simple: 规则很简单:
From this you can conclude that if you want to perform "raw" pointer arithmetic you have to cast to and from char*. 由此可以得出结论,如果要执行“原始”指针算法,则必须转换为char *。
So, by "work" I assume you mean "how do I dereference/perform pointer arithmetic on a void*
"? 所以,通过“工作”,我假设你的意思是“如何取消引用/执行
void*
指针算术void*
”? You can't; 你不能; you have to cast it, typically to a
char*
if you're just concerned with reading chunks of memory. 如果你只是关心阅读大块的内存,你必须把它强制转换为
char*
。 Of course, if that's the case, simply declare it as a char*
to begin with. 当然,如果是这种情况,只需将其声明为
char*
即可。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.