【问题标题】:Struct pointer cast as uint8_t * throws an error结构指针转换为 uint8_t * 会引发错误
【发布时间】:2012-05-06 22:14:41
【问题描述】:

在我的函数中,我为一个名为 messagePacket 的结构分配内存并填充它

struct messagePacket *packet = malloc(sizeof(struct messagePacket));
//fill

当我尝试将指针转换为 (uint8_t *) 时,gcc 会抛出一条警告:大整数隐式截断为无符号类型

sendBuf(..., (uint8_t *)packet);

我已经能够很好地执行以下操作,并且我知道我可以使用这种方法作为解决方法。我在这里是因为我宁愿从中学习也不愿解决它。

uint8_t *buf = malloc(sizeof(struct messagePacket));

struct messagePacket 的大小 = 1209 B。我最好的猜测是内存块超级大,我被存储在一个高内存地址中,例如 16 字节地址?但这不符合我可以 malloc 相同大小的 uint8_t * 的事实。

【问题讨论】:

  • sendBuf 是做什么的?
  • @cnicutar 我认为这并不重要,因为演员阵容似乎是个问题
  • @pivotnig 我认为这确实很重要,因为该演员阵容可能是多余的或完全错误的。按照标准,这已经是大错特错了。
  • sendBuf 接受 uint8_t *,创建类似的 uint8_t *recvBuf = sizeof(struct messagePacket),send() 的数据通过端口,select() 和 recv()数据
  • code #include <stdio.h> #include <stdlib.h> struct messagePacket { int a; int b[2000]; }; void sendBuf(char * d) { int c; c=*d; } int main() { struct messagePacket *packet = malloc(sizeof(struct messagePacket)); sendBuf((unsigned char*)packet); return 0; } 我看不到错误。

标签: c memory-management casting compiler-errors truncate


【解决方案1】:

我猜编译器会注意到你的结构大于 8 位,使用uint8_t 你只会寻址结构的第一个字节。 由于这似乎是有意的,您可以转换为(void *),然后转换为(uint8_t *)。 但是你应该告诉 sendBuf 缓冲区大小是sizeof(struct messagePacket)

【讨论】:

  • 编译器太聪明了,不适合这种双重铸造恶作剧。并且发送 buf 肯定会得到那个大小
【解决方案2】:

我认为警告是关于其他一些论点。请提供该行的完整代码、sendBuf() 函数的原型以及相关行的完整编译器警告。

一般来说,sendBuf() 函数应该使用const void * 而不是const uint8_t * 来发送数据。见@987654321@ 和朋友。

【讨论】:

  • 放松获胜。我需要更好地提出问题(即:至少发布完整的代码)。我将 sizeof(struct messagePacket) 传递给 uint8_t 类型的参数,该参数远远超出范围。我忽略了这一点,因为我的论点在不同的行上,编译器将我指向我最初询问的行
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-26
相关资源
最近更新 更多