简体   繁体   English

如何使用指针偏移量访问结构的成员

[英]how to access a member of a structure using a pointer offset

/* Trying to copy a value from member of one structure to another using pointers and structure offset: */ / *尝试使用指针和结构偏移将值从一个结构的成员复制到另一个结构:* /

enter code here

typedef struct
{
    uint8 Value;
    uint8 Status;
} sts;

typedef struct
{
   sts CC1;
   sts CC2;
   sts CC3;
   sts CC4;
} StructTypeWrite;

typedef struct
{
   uint8 CC1;
   uint8 CC2;
   uint8 CC3;
   uint8 CC4;
} StructTypeRead;   

static StructTypeWrite WriteVariable;
static StructTypeRead ReadVariable;

void main(void)
{
    StructTypeWrite *WritePtr;
    StructTypeRead *ValPtr;
    uint8 i;

    /* Just Writing Value in order to check */
    WriteVariable.CC1.Value = 5;
    WriteVariable.CC2.Value = 30;   
    WriteVariable.CC3.Value = 40;   
    WriteVariable.CC4.Value = 45;

    WritePtr = &WriteVariable;
    ValPtr = &ReadVariable;

    for(i=0; i<4; i++) 
    {
        /* Need to copy all the members value to another structure */
        *((uint8*)ValPtr + i) = *((sts*)(uint8*)WritePtr + i)->Value;
    }
}

error during compilation is : error #75: operand of "*" must be a pointer ((uint8 )ValPtr + i) = ((sts )(uint8*)WritePtr + i)->Value; 编译期间的错误是:错误#75:“*”的操作数必须是指针((uint8 )ValPtr + i)= ((sts )(uint8 *)WritePtr + i) - >值;

Can anyone help me where am i wrong ? 任何人都可以帮我,我错了吗?

You are correctly computing the pointer offsets. 您正确计算指针偏移量。 However, you are dereferencing too many times. 但是,您解除引用次数太多了。 The arrow notation -> dereferences a struct in C. So if you are using -> , you should not also be using * . 箭头符号->取消引用C中的结构。因此,如果您使用-> ,则不应使用* I corrected your code by using only the arrow to dereference. 我通过仅使用箭头取消引用来更正您的代码。 Like so: 像这样:

for(i=0; i<4; i++) 
{
    /* Need to copy all the members value to another structure */
    *((uint8*)ValPtr + i) = ((sts*)(uint8*)WritePtr + i)->Value;
}

Notice the star I removed right after the = on the assignment line. 注意我在分配线上的=之后删除的星号。

Edit: You should not compute pointer offsets like this in a struct, because different struct elements will be padded differently. 编辑:您不应该在结构中计算这样的指针偏移量,因为不同的结构元素将以不同方式填充。 Use the offsetof macro instead. 请改用offsetof宏。

Like so: 像这样:

uint8* newCC1Address = WritePtr + offsetof(StructTypeWrite, CC1);

This will ensure that the offset is correctly computed given the potential for different byte offsets due to padding. 这将确保在给定由于填充引起的不同字节偏移的可能性的情况下正确计算偏移。

Avoid accessing struct members using pointer offset. 避免使用指针偏移访问struct成员。 The compiler may add padding bytes to get a proper alignment. 编译器可以添加填充字节以获得正确的对齐。 see Data structure alignment Why don't you use arrays instead of structs? 请参阅数据结构对齐为什么不使用数组而不是结构? sts WriteVariable[4]; sts WriteVariable [4]; uint8 ReadVariable[4]; uint8 ReadVariable [4];

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

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