如何从C中的"原始"内存中读取/写入类型值?

dte*_*ech 7 c memory casting memory-access

我如何制作这样的作品?

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
Run Code Online (Sandbox Code Playgroud)

ziu*_*ziu 6

简单示例:将内存视为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
Run Code Online (Sandbox Code Playgroud)

您也可以使用整数,但是您必须注意一次设置的字节数.


wil*_*ser 5

规则很简单:

  • 每个指针类型(函数指针除外)都可以在 void* 之间进行转换,而不会丢失。
  • 您不能对 void* 指针执行指针算术,也不能取消引用它们
  • 根据定义,sizeof(char) 等于 1;因此,增加 char 指针意味着“原始”指针值“加 1”

由此您可以得出结论,如果您想执行“原始”指针算术,则必须在 char* 之间进行转换。