0

I have a nested structure of this type -

typedef struct {
    head     HEAD;  
    tail     TAIL;
    start    START;
    end      END;
}NODE;

I have a pointer to this nested structure -

 NODE* settings = malloc(sizeof(NODE));

and I pass this pointer to nested struct to a function. In the function, I need to access the individual structs within the main struct, to add the bytes within the struct. This is the function prototype -

int checksumVerify( NODE* settings)
{
    unsigned int i;
    unsigned char checksum = 0;

    //I need to access the size of individual structs from the pointer to main struct and then add all the bytes in the inner struct together.
    for (i = 0; i < sizeof(*settings)->HEAD; i++)
    {
        checksum += (char)(settings)->HEAD;
        settings++;
    }
    //Like wise I need to do it for the second struct as well
    for (i = 0; i < sizeof(*settings)->TAIL; i++)
    {
        checksum += (char)(settings)->TAIL);
        settings++;
    }
    return ((int)((checksum == 0) ? 1 : 0));
}

I do not know know the syntax to access the size of individual structs and accessing each entry in each of the individual struct is wrong here. What is the correct syntax for both?

SMG
  • 23
  • 8

1 Answers1

0

I know the syntax to access the size of individual structs and accessing each entry in each of the individual struct is wrong here. What is the correct syntax for both?

sizeof(*settings)->TAIL --> sizeof(settings->TAIL)

NODE* settings;
settings->HEAD.some_member_of_head;
settings->TAIL.some_member_of_tail;

Can I just loop with the size of individual struct and not access individual members within the inner struct?

char *p = (char*)&settings->HEAD;
for (size_t i = 0; i < sizeof(settings->HEAD); ++i)
    checksum += p[i];

But as @JimRhodes said: You should inform yourself about padding and packing.

Swordfish
  • 12,971
  • 3
  • 21
  • 43