我正在使用一个 UDP 协议(protocol)的实现,它发送一个类似于 char * 的套接字。我还定义了一个结构来按大小适应套接字的 header 和主体。就像:
#pragma once
typedef struct WHEATHER_STRUCT{
uint8_t packetID; // 9
uint16_t packetSize; // 11
uint8_t subpacketID; // 0
uint16_t subpacketOffset; // 0
uint8_t reserved; // 0
float cloudLayerAltitude; // 25000
}
我检查了这个套接字的大小,是 11 个字节。
我正在提高我对指针的了解,我正在尝试使用带偏移量的指针访问此变量。有一个例子:
Initial position of the struct: &(this->wheather_struct[0])
我试图使用这个内存地址来获取变量 packetID 的值。但这对我不起作用。
在得到这个解决方案后,我将用这句话定义一个偏移量来访问下一个值:
&(this->wheather_struct[0]) + 1 // Memory address of the next byte?
我有结构的第一个元素的内存地址,但我无法获取它的值。你能帮帮我吗?
If you could give me an example to access the value of cloudLayerAltitude using pointers with an offset could be awesome. Thank you.
最佳答案
如果 this->wheather_struct
是WHEATHER_STRUCT
结构的数组(或指向数组第一个元素的指针),那么它在内存中看起来像这样:
+--------------------+--------------------+--------------------+-----+ | wheather_struct[0] | wheather_struct[1] | wheather_struct[2] | ... | +--------------------+--------------------+--------------------+-----+
指向 weather_struct[0]
的指针将指向该数组的第一个元素。
如果向该指针加一,您将指向该数组的第二个元素。不是结构中的第二个字节。
要获得指向第二个字节的指针,您需要将指针 &weather_data[0]
视为指向字节的指针。
关于c++ - 使用 Pragma 以字节为单位适应套接字的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52925577/