如何打印出在C变量的内存内容是什么? [英] How to print out the memory contents of a variable in C?
本文介绍了如何打印出在C变量的内存内容是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我做了
双D = 234.5;
我要看看 D
[整8个字节]
如何做呢?
解决方案
双D = 234.5;/ * 1,使用工会* /
工会ü{
双D;
unsigned char型C [的sizeof(双)];
};
工会üTMP;
为size_t我;
tmp.d = D;
对于(i = 0; I<的sizeof(双); ++ I)
的printf(%02X \\ n,tmp.c [I]);/ * 2 *的memcpy /
unsigned char型数据[sizeof的D],
为size_t我;
的memcpy(数据,和D,sizeof的D);
对于(i = 0; I< sizeof的D组; ++ I)
的printf(%02X \\ n,数据[I]);/ * 3.使用指针unsigned char类型检查字节* /
无符号的char * p =(无符号字符*)和D;
为size_t我;
对于(i = 0; I< sizeof的D组; ++ I)
的printf(%02X \\ n,P [I]);
所有方法都告诉你的字节—但同样的双击
值可能在不同的系统,例如,由于不同的编码(罕见),或者不同的不同打印字节字节序。
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.
这篇关于如何打印出在C变量的内存内容是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文