开发者

Print a struct in C

开发者 https://www.devze.com 2023-02-17 19:57 出处:网络
I am trying to print a struct that is coming as an argument in a function in order to do some debugging.

I am trying to print a struct that is coming as an argument in a function in order to do some debugging.

Is there anyway I could print a structure's contents without knowing what it looks like, i.e. without printing each field explicitly? You see, depending on loads of different #defines the structure may look very differently, i.e. may have or not have different fields, so I'd like to find an easy way to do something like print_structure(my_structure).

NetBeans' debugger can do that for me, but unfortunately the code is开发者_如何转开发 running on a device I can't run a debugger on.

Any ideas? I suppose it's not possible, but at least there may be some macro to do that at compilation time or something?

Thanks!


You can always do a hex dump of the structure:

#define PRINT_OPAQUE_STRUCT(p)  print_mem((p), sizeof(*(p)))

void print_mem(void const *vp, size_t n)
{
    unsigned char const *p = vp;
    for (size_t i=0; i<n; i++)
        printf("%02x\n", p[i]);
    putchar('\n');
};


There is nothing like RTTI in C, only solution (apart from hex dump like above) is to #define dump function together with other #defines, ie.

#if _DEBUG

struct { ..... }
#define STRUCT_DUMP(x) printf(.....)

#else

struct { ..... } // other version
#define STRUCT_DUMP(x) printf(.....)    // other version dump

#endif
0

精彩评论

暂无评论...
验证码 换一张
取 消