【问题标题】:For looping struct members with a pointer to a struct用于使用指向结构的指针循环结构成员
【发布时间】:2019-04-17 08:50:58
【问题描述】:

我认为我的指针游戏生锈了,我似乎无法让 for 循环实现工作。这就像指针没有随着数组一起增加。 有什么建议吗?

我实现了我希望循环执行的“手动”版本。它按预期工作。

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;
};*/

我希望对此进行一些澄清,这样我就可以学习如何在未来避免这种情况!甚至可能是实现此类缓冲区的更好方法。

【问题讨论】:

  • 当你通过&amp;txobj时,这个逻辑cthis + ii > 0)应该指向哪里?
  • 如果你想尝试指针运算,你可以做uint8_t dataptr = cthis-&gt;tx; for (int i = 0; i &lt; 8; i++) { *(dataptr++) = arr[i]; }。顺便说一句:我建议用txstruct_t 中的#defineenum 值替换幻数8,并使用sizeof(cthis-&gt;tx) 来限制send 函数中的循环。
  • 是的,当然谢谢@Bodo。这只是一个快速而肮脏的测试 :) 但你是绝对正确的!

标签: c pointers struct arduino function-pointers


【解决方案1】:

cthis = cthis + i; 可以删除。这根本没有意义,因为这是一种未定义的尝试以某种方式将指针重置为struct。你不会在 unrolled 版本的循环中这样做,是吗?

循环的其他组件都很好。

【讨论】:

  • 我添加了 cthis = cthis + i;在绝望的愚蠢尝试中。因为它没有按预期工作。现在可以了..不知道我做了什么..经典..
猜你喜欢
  • 2023-03-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-24
相关资源
最近更新 更多