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...
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));
}
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.