简体   繁体   English

memset指针+偏移量

[英]memset pointer + offset

For example, I have: 例如,我有:

   DWORD pointer = 0x123456;
   DWORD offset = 0xABC;

I want to add offset to pointer and set the value at the address pointed by that pointer to 1.0f . 我想向指针添加offset并将该指针指向的地址的值设置为1.0f How do I give memset() a pointer and an offset as first argument? 如何给memset()一个指针和一个偏移量作为第一个参数?

DWORDs are the same as uint32_t's. DWORD与uint32_t相同。 Just add them together as you would with any other integer. 只需将它们加在一起即可,就像使用其他任何整数一样。

Also, while setting a float (I am assuming you're setting a float due to the 'f' after the '1.0'), I wouldn't use memset. 另外,在设置浮点数时(我假设您是由于'1.0'之后的'f'而设置浮点数),因此我不会使用memset。 Just cast the pointer to a float, and de-reference it like so: 只需将指针转换为浮点数,然后取消引用就可以了:

DWORD pointer = 0x123456;
DWORD offset = 0xABC;

pointer += offset;

float* float_pointer = reinterpret_cast<float*>(pointer);
*float_pointer = 1.0f;

This can be straightforward pointer arithmetic, but we've got a few preliminary issues to take care of first. 这可能是简单的指针算法,但首先要解决一些初步问题。

  1. Why is your pointer variable declared as a DWORD ? 为什么将pointer变量声明为DWORD We'll need a proper pointer type eventually. 最终我们将需要适当的指针类型。
  2. Why are you asking about memset , if you're trying to set a floating-point value? 如果要设置浮点值,为什么要问memset memset sets plain bit patterns; memset设置普通位模式; it's not much good for floating-point. 对于浮点运算没有太大好处。
  3. I assume your offset is supposed to be measured in bytes, not sizeof(float) . 我假设您的offset应该以字节为单位,而不是sizeof(float)

Anyway, computing the pointer you want could go something like this: 无论如何,计算所需的指针可能会如下所示:

float *fp = (float *)(pointer + offset);

[Notice that I perform the addition inside the parens, before the cast, so as to get a byte offset. [请注意,我在强制转换之前在括号内执行了加法运算,以获得字节偏移量。 If I instead wrote (float *)pointer + offset , it'd offset by `sizeof(float).] 如果我改写了(float *)pointer + offset ,它会被`sizeof(float)抵消。]

Once we've got that float pointer, we can set the location it points to to 1.0 in the usual way: 一旦有了该浮点指针,就可以按照通常的方式将其指向的位置设置为1.0

*fp = 1.0f;

Or we could set it to 0 using memset: 或者我们可以使用memset将其设置为0:

memset(fp, 0, sizeof(float));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM