0

I'm trying to fill byte/char array with memory address of float variable (array length is 4 bytes = pointer), but whatever I do it keeps getting float value instead of address:

float f = 20.0f;

memcpy(data, &f, sizeof(data));

Debugging it with:

printf("Array: %#X, %#X, %#X, %#X", data[0], data[1], data[2], data[3]);

...gives float value (20.0) in hex format:

Array: 0, 0, 0XA0, 0X41

What I need is memory address of float. I tried casting/dereferencing it in some different ways, but can't get it to work...

gsamaras
  • 71,951
  • 46
  • 188
  • 305
Zax Ftw
  • 81
  • 4
  • 10

2 Answers2

5

It's how memcpy works: it takes a pointer to data it will copy. Your data is pointer to float, so you need to pass pointer to pointer to float:

#include <cstring>

int main() {
   float f = 20.0f;
   float* pf = &f;
   char data[sizeof(pf)];
   memcpy(data, &pf, sizeof(data));
}
Andriy Tylychko
  • 15,967
  • 6
  • 64
  • 112
  • Maybe you should also mention that on a 64 bit machine (common, nowadays) a pointer should take 8 chars/byte. – Bob__ Oct 02 '17 at 23:22
  • @Bob__: sure, thanks! Zax Ftw: read above, and in general, better describe what you're doing in separate question and ask if it's a good thing to do – Andriy Tylychko Oct 02 '17 at 23:24
  • But this is for 32 bit, so pointer is 4 bytes, I didn't want to post more details because its completely unrelated and niche stuff. – Zax Ftw Oct 02 '17 at 23:47
0

For a C solution, save the hex data to a compound literal.

#include <stdio.h>

int main(void) {
  char data[sizeof (float*)];
  printf("%p\n", (void*) data);
  float f;
  printf("%p\n", (void*) &f);

  memcpy(data, &(float *){&f}, sizeof (float*));
  for (unsigned i = 0; i<sizeof data; i++) {
    printf("%02hhX ", data[i]);
  }
  puts("");
}

Output

0xffffcba8
0xffffcba4
A4 CB FF FF 00 00 00 00 

The address is valid until the end of the block.
Adjust endian/print order as desired.

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
  • Curious why this compound literaI doesn't compile in C++. I really like this one line solution, but getting too many brackets errors. – Zax Ftw Oct 03 '17 at 10:54
  • @ZaxFtw IIRC, C++ does not support _compound literal_. See [Are compound literals Standard C++?](https://stackoverflow.com/q/28116467/2410359) – chux - Reinstate Monica Oct 03 '17 at 12:12