开发者

Typecasting an integer to a character pointer in C

I have a function uint8_t EE_Write(uint8_t addr, uint8_t len, uint8_t * buf) that takes a pointer to some data that it will write to memory, and a uint16_t myword that I want to give it. The basic

EE_Write(0,sizeof(myword),&myword);

gives me the compiler warning "Indirection to different types ('unsigned int *const ' instead of 'unsigned char *const ')" Even when I typecast the word (int) to a byte 开发者_如何学JAVA(char), I received the exact same warning (and no amount of grouping with parenthesis helped).

EE_Write(0,sizeof(myword),&(uint8_t)myword);

Warnings go away with a union, but it's asinine to have to write it to another variable just to make the compiler happy.

union catbyte {
    uint16_t w;
    uint8_t b[2];
};

union catbyte mybytes;

mybytes.w = myword;
EE_Write(0,sizeof(myword),mybytes.b);


You could do:

EE_Write(0,sizeof(myword),(uint8_t *)&myword);

But the prefered way of doing this would be to define the function to take a void pointer like:

uint8_t EE_Write(uint8_t addr, uint8_t len, const void * buf);

And then the compiler shouldn't warn you about it for any pointer type you pass.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜