Fred
Fred

Reputation: 457

Print raw data in hex from struct containing pointers

As a peculiar continuation of a question of printing raw hex data from a struct: Printf raw data to a fixed length hex output

I have a struct that contains pointers to other data. Is there any simple way to printf this struct and the contents of the pointers as raw hex values in one continuous stream? When printing the hex values of B below using:

// @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]);

I naturally only get an address at myStruct.c (because that's what it is, I presume).

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

I tried manually making room for data in struct B with malloc and copying struct A over, but didn't seem to do the trick. Trying this out of mostly curiosity.

Upvotes: 1

Views: 931

Answers (1)

Acorn
Acorn

Reputation: 26126

When you are looping over struct B and printing void * c, you are printing the value of the pointer (i.e. the memory address).

Therefore, either you embed struct A directly in struct B (instead of a pointer); or the printing code is written so that it is aware of the pointer, dereferences it and prints that (you need to know how big the memory is there -- since you say // usually a struct A, let's assume the program knows; otherwise, you need to keep what is there; or at least its size).

Upvotes: 1

Related Questions