Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print a struct in C

Tags:

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!

like image 332
Albus Dumbledore Avatar asked Mar 18 '11 09:03

Albus Dumbledore


People also ask

Can I print a struct in C?

C/C++ does not support to print out struct's field name. This is a guide showing how to print struct field and value using macros.

How do I print a struct address?

In C, we can get the memory address of any variable or member field (of struct). To do so, we use the address of (&) operator, the %p specifier to print it and a casting of (void*) on the address.

What is struct in C?

A struct in the C programming language (and many derivatives) is a composite data type (or record) declaration that defines a physically grouped list of variables under one name in a block of memory, allowing the different variables to be accessed via a single pointer or by the struct declared name which returns the ...

Is struct available in C?

Structures (also called structs) are a way to group several related variables into one place. Each variable in the structure is known as a member of the structure. Unlike an array, a structure can contain many different data types (int, float, char, etc.).


1 Answers

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'); }; 
like image 115
Fred Foo Avatar answered Sep 28 '22 12:09

Fred Foo