gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 01:50:32 29 4
gpt4 key购买 nike

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

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:“*”的操作数必须是一个指针 ((uint8)ValPtr + i) = ((sts)(uint8*)WritePtr + i)->值;

谁能帮我看看哪里错了?

最佳答案

您正在正确计算指针偏移量。但是,您取消引用的次数太多了。箭头符号 -> 取消引用 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);

这将确保正确计算偏移量,因为填充可能会导致不同的字节偏移量。

关于c - 如何使用指针偏移访问结构的成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44093285/

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