简体   繁体   English

访问嵌套结构

[英]Accessing Nested Structure

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? 两者的正确语法是什么?

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) 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 . 但是正如@JimRhodes所说:您应该告知自己有关填充和打包的信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM