Search code examples
c++pointersembeddedpointer-arithmetic

Pointer arithmetic and portability


I'm writing an application and I had to do some pointers arithmetic. However this application will be running on different architecture! I was not really sure if this would be problematic but after reading this article, I thought that I must change it.

Here was my original code that I didn't like much:

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;
}

Pretty bad isn't it! Adding an int value to a u_char pointer! But then I changed to this:

const u_char* Frame::getPayload() const
{
  return &m_pLayerHeader[m_iHeaderLength];
}

I think now, the compiler is able to say how much to jump! Right? Is the operation [] on array considered as pointer arithmetic? Does it fix the portability problem?


Solution

  • p + i and &p[i] are synonyms when p is a pointer and i a value of integral type. So much that you can even write &i[p] and it's still valid (just as you can write i + p).

    The portability issue in the example you link was coming from sizeof(int) varying across platforms. Your code is just fine, assuming m_iHeaderLength is the number of u_chars you want to skip.