简体   繁体   English

用于访问 char 数组中的结构的 void 指针

[英]Void pointer to access structs in char array

I have a buffer, essentially an char array, filled with multiple different structs.我有一个缓冲区,本质上是一个 char 数组,里面填充了多个不同的结构。 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.这些结构是一个 header 结构和可能的“多个有效负载”结构。

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 ,它首先在缓冲区的 position 处初始化,然后在 Z099FB995346F339549F6E40F 之后的 position 处初始化,例如:

void *ptr;

ptr = &buffer;
ptr += sizeof(header);

This actually works fine - ie 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.这实际上工作正常 - 即指针指向正确的 memory 位置,我可以很好地检索(或插入)新的有效负载结构,但它确实会在 gcc 中生成警告。 warning: pointer of type 'void *' used in arithmetic . warning: pointer of type 'void *' used in arithmetic

What can I do to avoid this warning in this case?在这种情况下,我能做些什么来避免这个警告?

Use char * instead of a void *.使用 char * 而不是 void *。 The problem is it's not obvious what incrementing a void * is supposed to do.问题是增加 void * 应该做什么并不明显。 I'd expect this to be an error rather than a warning.我希望这是一个错误而不是警告。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM