Categories
c c++ double memory

How to print out the memory contents of a variable in C?

Suppose I do a

double d = 234.5;

I want to see the memory contents of d [the whole 8 bytes]

How do I do that?

double d = 234.5;
/* 1. use a union */
union u {
double d;
unsigned char c[sizeof(double)];
};
union u tmp;
size_t i;
tmp.d = d;
for (i=0; i < sizeof(double); ++i)
printf("%02x\n", tmp.c[i]);
/* 2. memcpy */
unsigned char data[sizeof d];
size_t i;
memcpy(data, &d, sizeof d);
for (i=0; i < sizeof d; ++i)
printf("%02x\n", data[i]);
/* 3. Use a pointer to an unsigned char to examine the bytes */
unsigned char *p = (unsigned char *)&d;
size_t i;
for (i=0; i < sizeof d; ++i)
printf("%02x\n", p[i]);

All the methods show you the bytes—but the same double value may print the bytes differently on different systems, e.g., due to different encodings (rare), or different endianness.