简体   繁体   English

用于使用结构体指针循环结构体成员

[英]For looping struct members with a pointer to a struct

I think my pointer game is rusty, I can't seem to get the for loop implementation to work. 我认为我的指针游戏生锈了,我似乎无法使for循环实现正常工作。 It's like the pointer isn't incremented along with the array. 就像指针没有随数组增加一样。 Any suggestions? 有什么建议么?

I implemented a "manual" version of what i want the loop to do. 我实现了希望循环执行的“手动”版本。 It worked as expected. 它按预期工作。

typedef struct txstruct_t
{
    uint8_t tx[8];
    void(*send)(struct txstruct_t *cthis, uint8_t arr[8]);

}txstruct_t;

void send(txstruct_t *cthis, uint8_t arr[8]);


void loop() 
{
    txstruct_t txobj;
    uint8_t buf[8] = { 1, 0, 1, 0, 1, 0, 1, 0 };
    send(&txobj, buf);

}

// This works
void send(txstruct_t *cthis, uint8_t arr[8])
{
    cthis->tx[0] = arr[0];
    cthis->tx[1] = arr[1];
    cthis->tx[2] = arr[2];
    cthis->tx[3] = arr[3];
    cthis->tx[4] = arr[4];
    cthis->tx[5] = arr[5];
    cthis->tx[6] = arr[6];
    cthis->tx[7] = arr[7];

    return;
};

/*
//This doesn't work :(
void send(txstruct_t *cthis, uint8_t arr[8])
{

    for (int i = 0; i < 8; i++)
    {
        cthis = cthis + i;
        cthis->tx[i] = arr[i];
    }

    return;
};*/

I would love some clarification on this, so I could learn how to avoid this in the future! 我希望对此有所澄清,以便将来可以避免这种情况! Maybe even a better method of implementing such buffers. 甚至可能是实现此类缓冲区的更好方法。

cthis = cthis + i; can be removed. 可以删除。 It makes no sense at all as it's an undefined attempt to somehow reset the pointer to the struct . 这根本没有任何意义,因为这是一次未定义的尝试,以某种方式将指针重置为struct You don't do that in the unrolled version of the loop, do you? 您不在循环的展开版本中这样做,对吗?

The other components of the loop are fine. 循环的其他组件也不错。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM