C语言 在 C 中打印结构

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5349896/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 08:05:37  来源:igfitidea点击:

Print a struct in C

cprintingstruct

提问by Albus Dumbledore

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

我正在尝试打印struct作为函数中的参数出现的一个,以便进行一些调试。

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).

无论如何我可以在不知道结构的内容的情况下打印它的内容,即无需明确打印每个字段?你看,根据不同#defines 的负载,结构可能看起来非常不同,即可能有或没有不同的字段,所以我想找到一种简单的方法来做类似的事情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.

NetBeans 的调试器可以为我做到这一点,但不幸的是代码在我无法运行调试器的设备上运行。

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!

谢谢!

回答by Fred Foo

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

回答by pma_

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.

C 中没有像 RTTI 那样的东西,唯一的解决方案(除了上面的十六进制转储)是#define 转储函数与其他 #defines 一起,即。

#if _DEBUG

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

#else

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

#endif