帮助将指针转换为联合
我正在研究 C 固件项目。我有一个联合,定义为,
typedef union {
unsigned long value;
unsigned char bytes[4];
} LONGVALUE;
我还有一个具有此原型的函数,
char sendHexToASCII_UART(char *msg, int cnt);
以及一个 LONGVALUE 类型的变量定义为,
LONGVALUE countAddr;
问题: 我用数组 (tempBuff1) 中的值填充联合变量的各个字节,然后我想将联合中第一个元素的地址传递给一个函数,该函数将其打印到 UART。在我的函数调用 sendHexToASCII_UART((int *)countAddr.bytes[0], 4);
上,我收到一条编译器警告,提示“从不同大小的整数转换为指针”。有人可以解释一下为什么我会出现这种情况以及如何让它消失吗?注意:将 (int *) 转换更改为 (char *) 会导致相同的警告。
countAddr.bytes[0] = tempBuff1[COUNT_ADDR - PWRD_ADDRESS];
countAddr.bytes[1] = tempBuff1[COUNT_ADDR - PWRD_ADDRESS + 1];
countAddr.bytes[2] = tempBuff1[COUNT_ADDR - PWRD_ADDRESS + 2];
countAddr.bytes[3] = tempBuff1[COUNT_ADDR - PWRD_ADDRESS + 3];
sendHexToASCII_UART((int *)countAddr.bytes[0], 4);
I am working on C firmware project. I have a union that is defined as,
typedef union {
unsigned long value;
unsigned char bytes[4];
} LONGVALUE;
I also have a function that has this prototype,
char sendHexToASCII_UART(char *msg, int cnt);
and a variable of type LONGVALUE defined as,
LONGVALUE countAddr;
THE PROBLEM:
I fill the individual bytes of the union variable with values from an array (tempBuff1), I then want to pass the address of the first element in the union to a function that will print it to the UART. On my function call sendHexToASCII_UART((int *)countAddr.bytes[0], 4);
, I get a compiler warning saying "cast to pointer from integer of different size". Can someone explain why I am getting this and how I can make it go away? NOTE: Changing the (int *) cast to (char *) causes the same warning.
countAddr.bytes[0] = tempBuff1[COUNT_ADDR - PWRD_ADDRESS];
countAddr.bytes[1] = tempBuff1[COUNT_ADDR - PWRD_ADDRESS + 1];
countAddr.bytes[2] = tempBuff1[COUNT_ADDR - PWRD_ADDRESS + 2];
countAddr.bytes[3] = tempBuff1[COUNT_ADDR - PWRD_ADDRESS + 3];
sendHexToASCII_UART((int *)countAddr.bytes[0], 4);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
为什么不只是:
甚至更好:
Why not just:
or even better:
sendHexToASCII_UART((int *)(&countAddr.bytes[0]), 4);
或:
sendHexToASCII_UART((int *)(countAddr.bytes), 4);
sendHexToASCII_UART((int *)(&countAddr.bytes[0]), 4);
or:
sendHexToASCII_UART((int *)(countAddr.bytes), 4);
表达式的值
是一个无符号字符(数组中的第一个字节),您将其转换为 int 指针,因此会出现警告。正如 Oli 所说,您必须删除
[0]
才能获得指向数组的指针,这就是您想要的。The value of the expression
is an unsigned char (the first byte in your array), which you cast to an int pointer, hence the warning. As Oli said, you must remove the
[0]
to get a pointer to the array, which is what you want.或者在不创建 LONGVALUE 类型变量的情况下尝试此操作
or try this without creating variable of LONGVALUE type