gpt4 book ai didi

c - 访问嵌套结构

转载 作者:行者123 更新时间:2023-11-30 16:27:31 26 4
gpt4 key购买 nike

我有一个这种类型的嵌套结构 -

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

我有一个指向这个嵌套结构的指针 -

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

我将这个指向嵌套结构的指针传递给函数。在函数中,我需要访问主结构中的各个结构,以在结构中添加字节。这是函数原型(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 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];

但正如 @JimRhodes 所说:您应该告知自己 padding and packing .

关于c - 访问嵌套结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52708788/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com