访问 char 数组中结构的空指针
我有一个缓冲区,本质上是一个字符数组,其中填充了多个不同的结构。这些结构需要在这样的缓冲区中传递,因为它是我读/写到套接字的东西。这些结构是一个标头结构,也可能是“多个有效负载”结构。
只是为了说明,它看起来像这样:
unsigned char buffer[buflen];
struct header *head;
struct payload1 *p1;
struct payload2 *p2;
etc...
现在,当我尝试填充此缓冲区或从此缓冲区检索时,我使用了 void *ptr
,它首先在然后在标头后面的位置稍后放置缓冲区,如下所示:
void *ptr;
ptr = &buffer;
ptr += sizeof(header);
这实际上工作正常 - 即指针指向正确的内存位置,我可以很好地检索(或插入)新的有效负载结构,但它确实会生成警告海湾合作委员会。 警告:算术中使用了“void *”类型的指针
。
在这种情况下我该怎么做才能避免出现此警告?
I have a buffer, essentially an char array, filled with multiple different structs. The structs needs to be passed in a buffer like this because it is something I read/write to a socket. The structs are one header struct and possibly "multiple payload" structs.
Just to illustrate, it looks like this:
unsigned char buffer[buflen];
struct header *head;
struct payload1 *p1;
struct payload2 *p2;
etc...
Now, when I try to fill this buffer, or retrieve from this buffer, I've used a void *ptr
where it is first initialized at the position of the buffer then later at the position after the header, like this:
void *ptr;
ptr = &buffer;
ptr += sizeof(header);
This actually works fine - i.e. the pointer points to the correct memory location and I can retrieve (or insert) a new payload struct just fine, but it does however generate a warning in gcc. warning: pointer of type ‘void *’ used in arithmetic
.
What can I do to avoid this warning in this case?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用 char * 而不是 void *。问题是递增 void * 应该做什么并不明显。我希望这是一个错误而不是警告。
Use char * instead of a void *. The problem is it's not obvious what incrementing a void * is supposed to do. I'd expect this to be an error rather than a warning.