如何使用指针偏移

时间:2017-05-21 04:45:23

标签: c

/ *尝试使用指针和结构偏移将值从一个结构的成员复制到另一个结构:* /

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;
    }
}
编译时出现

错误: 错误#75:&#34; *&#34;的操作数必须是指针             ((uint8 )ValPtr + i)= ((sts )(uint8 *)WritePtr + i) - &gt; Value;

任何人都可以帮助我,我错了吗?

2 个答案:

答案 0 :(得分:2)

您正确计算指针偏移量。但是,您解除引用次数太多了。箭头符号->取消引用C中的结构。因此,如果您使用->,则不应使用*。我通过仅使用箭头取消引用来更正您的代码。像这样:

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

请注意我在分配行=之后删除的星号。

编辑:您不应该在结构中计算这样的指针偏移量,因为不同的结构元素将以不同方式填充。请改用offsetof宏。

像这样:

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

这将确保在给定由于填充引起的不同字节偏移的可能性的情况下正确计算偏移量。

答案 1 :(得分:1)

避免使用指针偏移访问struct成员。 编译器可以添加填充字节以获得正确的对齐。 见Data structure alignment 为什么不使用数组而不是结构? sts WriteVariable [4]; uint8 ReadVariable [4];