C++如何直接访问内存

Cod*_*ith 1 c++ memory

假设我已经用C++手动分配了大部分内存,比如10 MB.

说它的哎呀我想在这个区域的中间存储几个位.

我如何获得该位置的记忆?

我知道访问原始内存的唯一方法是使用数组表示法.

Som*_*ude 9

数组表示法适用于此,因为分配的内存可以看作是一个大数组.

// Set the byte in the middle to `123`
((char *) memory_ptr)[5 * 1024 * 1024] = 123;
Run Code Online (Sandbox Code Playgroud)

char如果指针是另一种类型,我会指向一个指针.如果它已经是char指针,则不需要类型转换.


如果您只想设置一个位,请将存储器视为具有8000万个独立位的巨型位域.要找到所需的位,比如位号40000000,首先必须找到它所在的字节,然后找到该位.这是通过正常除法(找到char)和modulo(找到位)来完成的:

int wanted_bit = 40000000;

int char_index = wanted_bit / 8;  // 8 bits to a byte
int bit_number = wanted_bit % 8;

((char *) memory_ptr)[char_index] |= 1 << bit_number;  // Set the bit
Run Code Online (Sandbox Code Playgroud)


rmh*_*tog 7

数组表示法只是编写指针的另一种方式.您可以使用它,或直接使用指针:

char *the_memory_block = // your allocated block.
char b = *(the_memory_block + 10); // get the 11th byte, *-operator is a dereference.
*(the_memory_block + 20) = b; // set the 21st byte to b, same operator.
Run Code Online (Sandbox Code Playgroud)

memcpy,memzero,memmove,memcmp和其他人也可能是非常有用的,就像这样:

char *the_memory_block = // your allocated block.
memcpy(the_memory_block + 20, the_memory_block + 10, 1);
Run Code Online (Sandbox Code Playgroud)

当然这段代码也是一样的:

char *the_memory_block = // your allocated block.
char b = the_memory_block[10];
the_memory_block[20] = b;
Run Code Online (Sandbox Code Playgroud)

这是这样的:

char *the_memory_block = // your allocated block.
memcpy(&the_memory_block[20], &the_memory_block[10], 1);
Run Code Online (Sandbox Code Playgroud)

另外,一个并不比另一个更安全,它们完全相同.