c - 结构中数组的值仍在变化

标签 c arrays structure

我有一个问题。我将一些值写入我的数组,我想发送句柄以初始化框架以连接我的设备,但是当我从结构中获取结构时,我的数据覆盖了我想要的另一个值。

有我的 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];};

ma​​in.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);}

我的框架的输出不是我需要的。数据覆盖了 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是output->cmd,下一个是output->data,[8-12],但不是我的数组:)

有什么建议吗?

谢谢

最佳答案

编译代码时,您会看到以下警告。

warning: passing argument 1 of 'handlePackets' from incompatible pointer type
note: expected 'struct _PacketData *' but argument is of type 'struct _PacketData **'

问题的原因是您的函数(handlePacketssendPacket)采用指向 struct _PacketData 的指针,而不是指向指针的指针. 您需要将 struct _PacketData * outputOutPack; 更改为 struct _PacketData outputOutPack;

当您为函数提供指向指针的指针时,您实际上在做的是取消引用您分配给堆栈上指针类型的内存,这会导致未定义的行为并可能破坏您的堆栈。

关于c - 结构中数组的值仍在变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41066728/

相关文章:

c - 释放 malloc 不会删除 char 数据

c - 如何使用有故障的内核模块 - FC19 使系统崩溃?

javascript - 过滤一个对象以获取另一个数组中的值

python - 如何使用loadtxt在python中的同一个数组中加载多个文件?

image - 图像的结构如何

c - C 中的 R 包依赖于另一个 R 包

c++ - 如何判断 Microsoft Print to PDF 打印机驱动程序何时完成?

c - 为什么将指针传递给函数后访问多维数组的指针会返回段错误?

c - 数组与 C 编程语言中的结构体和 union 有何不同?

structure - Qooxdoo大型应用结构