我有问题。我写了一些值到我的数组,我想发送句柄到inicialize框架连接我的设备,但是当我拿起结构我的数据从结构覆盖另一个值比我想要的。
有我的foo:
int handlePackets (struct _PacketData * outputPacket, uint8_t command){
outputPacket->addr = SERIAL;
outputPacket->length = 0;
outputPacket->cmd = command;
switch (outputPacket->cmd)
{
case CMD_SET_OUTPUT:
outputPacket->length = 0x06;
outputPacket->data[0] = 0x80;
outputPacket->data[1] = 0x3F;
outputPacket->data[2] = 0x10;
outputPacket->data[3] = 0x40;
outputPacket->data[4] = 0x30;
return COMM_FRAME_OK;
}
return COMM_FRAME_OK;
}
int sendPacket (struct _PacketData * outputPacket, uint8_t * buffer){
int cntr = 0, x;
buffer[cntr++] = STX;
buffer[cntr++] = outputPacket->addr >> 24;
buffer[cntr++] = outputPacket->addr >> 16;
buffer[cntr++] = outputPacket->addr >> 8;
buffer[cntr++] = outputPacket->addr & 0xff;
buffer[cntr++] = outputPacket->length >> 8;
buffer[cntr++] = outputPacket->length & 0xff;
buffer[cntr++] = outputPacket->cmd;
for (x = 0; x < outputPacket->length -1 ; x++)
{
buffer[cntr++] = outputPacket->data[x];
}
crc = calcCrcBuffer (buffer + 1, cntr - 1);
buffer[cntr++] = (unsigned char) (crc >> 8); //crc high byte
buffer[cntr++] = (unsigned char) (crc & 0xff); //crc low byte
buffer[cntr++] = ETX;
return cntr;
}
结构
struct _PacketData{
uint32_t addr;
uint16_t length;
uint8_t cmd;
uint8_t data[256];};
的main.c
int main(void) {
struct _PacketData * outputOutPack;
uint8_t tab[256];
int i;
uint8_t *buffer = tab;
handlePackets(&outputOutPack,CMD_SET_OUTPUT );
result = sendPacket(&outputOutPack, buffer);}
我的画面输出并不像我需要的那样。数据覆盖了缓冲区[cntr]中的值,但我不知道为什么。
输出:
[0] = 0x82
[1] = 00
[2] = 0x18
[3] = 0xb0
[4] = 0xa5
[5] = 00
[6] = 0x6
[7] = 0x78
[8] = 0x82
[9] = 00
[10] = 0x18
[11] = 0xb0
[12] = 0xa5
[13] = 0x64
[14] = 0xfe
[15] = 0x83
位置7是输出 - > cmd,接下来是输出 - >数据,[8-12],但它不是我的数组:)
有什么建议吗?
由于
答案 0 :(得分:1)
编译代码时,您会看到以下警告。
warning: passing argument 1 of 'handlePackets' from incompatible pointer type
note: expected 'struct _PacketData *' but argument is of type 'struct _PacketData **'
问题的原因是你的函数(handlePackets
和sendPacket
)获取指向struct _PacketData
指针的指针。
您需要将结构_PacketData * outputOutPack;
更改为struct _PacketData outputOutPack;
当您使用指向指针的函数提供函数时,您实际上正在做的是取消引用您在堆栈上分配给指针类型的内存,这会导致未定义的行为并可能损坏您的堆栈。