Print a struct in C

拈花ヽ惹草 提交于 2019-12-18 11:07:19

问题


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!


回答1:


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');
};



回答2:


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


来源:https://stackoverflow.com/questions/5349896/print-a-struct-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!