将地址分配到分配内存的四个字节

时间:2013-09-17 01:43:49

标签: c++ memory dynamic-allocation memset

编辑:感谢Ipmcc,他在评论中给了我一个解决方案。

我想使用memset将四字节地址分配到我动态分配的前四个字节的内存中。下面显示了我想做的评论的示例。我试图找出如何做到这一点或者弄清楚自己的所有尝试都没有成功。

非常感谢任何帮助,谢谢。

int main(void)
{
  // Define and assign eight bytes of memory
  unsigned char *data1 = new unsigned char [8];
  unsigned char *data2 = new unsigned char [8];

  // Set all eight bytes in both data1 and data2 to 0x00
  memset(data1, 0x00, 8);
  memset(data2, 0x00, 8);

  // Lets say that the address of *data1 is: 00508d30
  // Lets say that the address of *data2 is: 0050b180

  // I want to set the first four bytes in data1 to the
  // address of data2, so it would look something like this...
  memset(data1, 0x00, 1); ++data1;
  memset(data1, 0x50, 1); ++data1;
  memset(data1, 0xB1, 1); ++data1;
  memset(data1, 0x80, 1);
  data1 -= 3; // Reset pointer

  // But of course this is in no way practical or viable
  // since the addresses change each time (also it's not a good
  // practice to hard-code things in anyway). So I'm wondering
  // if there's a proper/feasible way to do this.

  return 0;
}

0 个答案:

没有答案