horizon
horizon

Reputation: 31

How to print the value of struct members in c (with a pointer to a struct)

I'm trying to debug a program. There is a function being called prv_write()

static uint8_t prv_write(uint16_t instanceId,
                     int numData,
                     lwm2m_data_t * dataArray,
                     lwm2m_object_t * objectP)

This function is being passed (3rd argument) a pointer to a struct lwm2m_data_t which is defined as:

typedef struct _lwm2m_data_t lwm2m_data_t;

struct _lwm2m_data_t
{
    lwm2m_data_type_t type;
    uint16_t    id;
    union
    {
        bool        asBoolean;
        int64_t     asInteger;
        double      asFloat;
        struct
        {
            size_t    length;
            uint8_t * buffer;
        } asBuffer;
        struct
        {
            size_t         count;
            lwm2m_data_t * array;
        } asChildren;
        struct
        {
            uint16_t objectId;
            uint16_t objectInstanceId;
        } asObjLink;
     } value;
};

Could somebody explain how I could print the values of length and buffer inside the function prv_write() ? I don't really understand at this stage structs inside structs.

Ideally I'd like to print the values of all the struct members so that I can fully debug the system.

Upvotes: 1

Views: 1132

Answers (1)

zmo
zmo

Reputation: 24812

well to print it you can simply do:

for (int i=0; i<dataArray->value.asbuffer.length; ++i)
    printf("%d ", dataArray->value.asBuffer.buffer[i]);
printf("\n");

if you need to do it in several places of your code, you can make a macro for that:

#define SHOW_LWM2M_DATA(DA) do { \
    for (int i=0; i< (DA)->value.asbuffer.length; ++i) \
        printf("%d", (DA)->value.asBuffer.buffer[i]); \
    printf("\n"); } while (0)

(the do { } while(0) is only there to make the macro behave like a normal function)

and use that macro in many places of your code, as it evolves:

pipSHOW_LWM2M_DATA(dataArray);

but if you want to introspect that part of the code, my advice to you is to use gdb (or lldb), and setup a watchpoint or a breakpoint use its print function to lookup the values, it will print the structs and arrays easily.

Upvotes: 2

Related Questions