easy way to display the contents of data structures in C?
For debugging purposes, I find it useful to display the contents of data structures. (In Python for example, I would just do "print some_dict_name").
Can this be achieved in C this easy too by using a standard library, or do I have to implement this m开发者_如何转开发yself depending on the data structure ?
Consider the following code, where I have to iterate over the StructArray again to display all of its contents.
#include <stdio.h>
struct SomeStruct {
int id;
};
int main() {
struct SomeStruct StructArray[10];
int x = 0;
for (x = 0; x < 10; x++) {
StructArray[x].id = x;
}
for (x = 0; x < 10; x++) {
printf("StructArray[%d].id = %d\n", x, StructArray[x].id);
}
return 0;
}
You need to implement it yourself per data type.
C doesn't have a type system where you can dynamically or statically visit each part of each type.
If you are live-debugging with something like gdb though, its inteligent enough to read debugging info and print type contents. But you can't do that from the program itself, there is no such a thing as introspection for C types.
A really hackish way would be compiling your program with debug information, and build a debugging library into the program to read the debugging information from the program itself in runtime. Parse what should be parsed from it, and print the struct accordingly.
That's a project on its own though.
Or, you could use something like DDD, the Data Display Debugger.
精彩评论