我有这种类型的嵌套结构-
typedef struct {
head HEAD;
tail TAIL;
start START;
end END;
}NODE;
我有一个指向此嵌套结构的指针-
NODE* settings = malloc(sizeof(NODE));
,然后将此指向嵌套结构的指针传递给函数。在函数中,我需要访问主结构中的各个结构,以在结构中添加字节。这是函数原型-
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));
}
我不知道访问单个结构的大小和访问每个单个结构中每个条目的语法在这里是错误的。两者的正确语法是什么?
答案 0 :(得分:0)
我知道访问单个结构的大小和访问每个单个结构中每个条目的语法在这里是错误的。两者的正确语法是什么?
sizeof(*settings)->TAIL
-> sizeof(settings->TAIL)
NODE* settings;
settings->HEAD.some_member_of_head;
settings->TAIL.some_member_of_tail;
我可以仅根据单个结构的大小进行循环,而不能访问内部结构内的单个成员吗?
char *p = (char*)&settings->HEAD;
for (size_t i = 0; i < sizeof(settings->HEAD); ++i)
checksum += p[i];
但是正如@JimRhodes所说:您应该将padding and packing告知自己。