用于使用指向结构的指针循环结构成员
For looping struct members with a pointer to a struct
我觉得我的指针游戏生锈了,我似乎无法让 for 循环实现工作。这就像指针没有随着数组一起递增。
有什么建议吗?
我实现了一个 "manual" 版本的循环功能。它按预期工作。
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;
};*/
我希望得到一些澄清,这样我以后就可以学习如何避免这种情况!甚至可能是实现此类缓冲区的更好方法。
cthis = cthis + i;
可以去掉。它根本没有任何意义,因为它是一种未定义的尝试,以某种方式将指针重置为 struct
。您不会在 unrolled 版本的循环中这样做,对吗?
循环的其他组件没问题。
我觉得我的指针游戏生锈了,我似乎无法让 for 循环实现工作。这就像指针没有随着数组一起递增。 有什么建议吗?
我实现了一个 "manual" 版本的循环功能。它按预期工作。
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;
};*/
我希望得到一些澄清,这样我以后就可以学习如何避免这种情况!甚至可能是实现此类缓冲区的更好方法。
cthis = cthis + i;
可以去掉。它根本没有任何意义,因为它是一种未定义的尝试,以某种方式将指针重置为 struct
。您不会在 unrolled 版本的循环中这样做,对吗?
循环的其他组件没问题。