[英]storing 16 bit variable to dereferenced variable writes 32 bits
Consider the following: 考虑以下:
// main.h
struct
{
uint16_t aChargeOption0;
uint16_t aChargeOption1;
} oBattChargerInfo;
typedef struct CHGRRM
{
uint16_t nRegIndex;
uint8_t nDataType;
uint32_t nDataWidth;
uint32_t nRegAddress;
bool IsWritable;
bool HasBits;
uint32_t nBitStoreStart;
uint32_t nBitStoreEnd;
int *ptrToData;
} chargerRegMap_t;
extern chargerRegMap_t charger_reg_map[];
// main.c
chargerRegMap_t charger_reg_map[] =
{
{ &oBattChargerInfo.aChargeOption0 },
{ &oBattChargerInfo.aChargeOption1 },
};
// code to store a variable to the de-referenced variable
uint16_t aFinalBuff=0x00;
aFinalBuff=buff[1]<<8; // buff[0] and buff[1] is uint8
aFinalBuff=aFinalBuff+buff[0];
*charger_reg_map[nRegIndex].ptrToData=aFinalBuff;
When I store the first variable ( charger_reg_map[0].ptrToData
which in the first case is oBattChargerInfo.aChargeOption0
) the 16 bit variable overwrites the adjacent variable oBattChargerInfo.aChargeOption1
. 当我存储第一个变量( charger_reg_map[0].ptrToData
,在第一种情况下是oBattChargerInfo.aChargeOption0
)时,16位变量会覆盖相邻变量oBattChargerInfo.aChargeOption1
。 Other than setting each variable in my oBattChargerInfo
structure to 32 bits each, is there another solution? 除了将我的oBattChargerInfo
结构中的每个变量设置为32位之外,还有另一种解决方案吗? It seems strange that a dereferenced variable would work this way. 一个解除引用的变量会以这种方式工作似乎很奇怪。
I tried *charger_reg_map[nRegIndex].ptrToData=(uint16_t)aFinalBuff; 我试过* charger_reg_map [nRegIndex] .ptrToData =(uint16_t)aFinalBuff; to make clear my intention. 说清楚我的意图。 Didn't matter. 没关系。
What am I doing wrong here? 我在这做错了什么?
If you want differently-sized variables, there is no pointer type you can use to write to all of them. 如果您想要不同大小的变量,则没有可用于写入所有变量的指针类型。
The design is a bit brittle, since you would need to know which member your pointer is pointing to, or at least its type. 设计有点脆弱,因为您需要知道指针指向哪个成员,或者至少知道它的类型。
I think a better option would be to do the work with memcpy
through a function, and add a 'size' member to chargerRegMap_t
for sanity checking. 我认为更好的选择是通过函数使用memcpy
进行工作,并将“size”成员添加到chargerRegMap_t
以进行完整性检查。
Something like 就像是
void write_data(chargerRegMap_t* map, void* data, size_t size)
{
assert(size == map->data_size);
memcpy(map->ptrToData, data, size);
}
/* ... */
uint16_t aFinalBuff = 0x00;
aFinalBuff = buff[1] << 8;
aFinalBuff = aFinalBuff + buff[0];
write_data(charger_reg_map + nRegIndex, &aFinalBuff, sizeof(aFinalBuff));
I would probably add a macro to that as well, to eliminate sizeof
typos and make it less tedious: 我可能会添加一个宏,以消除拼写错误的sizeof
并使其不那么乏味:
#define WRITE_DATA(map, data) write_data(map, &data, sizeof(data))
/* ... */
WRITE_DATA(charger_reg_map + nRegIndex, aFinalBuff);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.