我有一个指向要在一个地址范围内逐字节移动的结构的指针。我有一种可行的方法,但在我看来却很难看。不幸的是,“不错”的方法行不通。这是一个最小的示例:
#include <stdint.h>
typedef struct {
uint32_t a;
uint32_t b;
} s_t;
int main( int argc, char** argv )
{
uint32_t address = 17;
s_t* ps = (s_t*) address;
// ugly
uint8_t* gna = (uint8_t*) ps;
++gna;
ps = (s_t*) gna;
// nice
++((uint8_t*) ps);
}
Run Code Online (Sandbox Code Playgroud)
编译器在“ nice”部分报告错误:
% gcc test.c -o test.bin
test.c: In function 'main':
test.c:17:5: error: lvalue required as increment operand
++((uint8_t*) ps);
^
Run Code Online (Sandbox Code Playgroud)
我理解该错误,但我认为强制转换为uint8_t *会创建一个左值。显然,我错了。
有没有办法使它更好?