我正在编写一个应用程序,我必须进行一些指针运算。然而,这个应用程序将在不同的架构上运行!我不太确定这是否会有问题,但在阅读后 this article ,我想我必须改变它。
这是我不太喜欢的原始代码:
class Frame{
/* ... */
protected:
const u_char* const m_pLayerHeader; // Where header of this layer starts
int m_iHeaderLength; // Length of the header of this layer
int m_iFrameLength; // Header + payloads length
};
/**
* Get the pointer to the payload of the current layer
* @return A pointer to the payload of the current layer
*/
const u_char* Frame::getPayload() const
{
// FIXME : Pointer arithmetic, portability!
return m_pLayerHeader + m_iHeaderLength;
}
很糟糕是吧!将 int
值添加到 u_char
指针!但后来我改成了这样:
const u_char* Frame::getPayload() const
{
return &m_pLayerHeader[m_iHeaderLength];
}
我想现在,编译器可以说跳多少了!正确的?数组上的操作 []
是否被视为指针算术?它是否解决了可移植性问题?
最佳答案
p + i
和 &p[i]
是同义词,当 p
是指针而 i
是值时的整体类型。如此之多以至于您甚至可以编写 &i[p]
并且它仍然有效(就像您可以编写 i + p
一样)。
您链接的示例中的可移植性问题来自 sizeof(int)
因平台而异。您的代码很好,假设 m_iHeaderLength
是您要跳过的 u_char
的数量。
关于c++ - 指针算法和可移植性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13375259/