从包含指针的struct中以十六进制格式打印原始数据

时间:2018-05-10 02:33:38

标签: c pointers hex printf

作为从结构中打印原始十六进制数据的问题的特殊延续:Printf raw data to a fixed length hex output

我有一个包含指向其他数据的指针的结构。是否有任何简单的方法来将此结构指针的内容作为原始十六进制值打印在一个连续流中?使用以下方法打印下面B的十六进制值时

// @note not actually valid code
struct B myStruct;
struct A myOtherStruct;
myStruct.c = &myOtherStruct;
unsigned char * p = (unsigned char *)myStruct;

for(int i = 0; i < sizeof(struct B) + sizeof(struct A); i++) // 
  printf("%02x ", p[i]);

我自然只会在myStruct.c获得一个地址(因为我认为这就是它)。

struct A
{
  int a;
  char b;
};
struct B
{
  int a;
  char b;
  void * c; // usually a struct A, ignore type-safety for simplicity 
};

我尝试使用struct B手动为malloc中的数据腾出空间并复制struct A,但似乎没有做到这一点。试图摆脱好奇心。

1 个答案:

答案 0 :(得分:1)

当您循环struct B并打印void * c时,您将打印指针的值(即内存地址)。

因此,您要么struct A直接嵌入struct B(而不是指针);或编写打印代码,以便它知道指针,取消引用它并打印出来(你需要知道存储器有多大 - 因为你说// usually a struct A,让我们假设程序知道;否则,你需要保留那里的东西;或者至少它的大小。

相关问题