Search code examples
c++ctypessemanticsoffset

Is it appropriate to use off_t for non-byte offsets?


Suppose I'm writing a function which takes a float a[] and an offset, into this array, and returns the element at that offset. Is it reasonable to use the signature

float foo(float* a, off_t offset);

for it? Or is off_t only relevant to offsets in bytes, rather than pointer arithmetic with aribtrary element sizes? i.e. is it reasonable to say a[offset] when offset is of type off_t?

The GNU C Library Reference Manual says:

off_t
     This is a signed integer type used to represent file sizes. 

but that doesn't tell me much.

My intuition is that the answer is "no", since the actual address used in a[offset] is the address of a + sizeof(float) * offset , so "sizeof(float) * offset" is an off_t, and sizeof(float) is a size_t, and both are constants with 'dimensions'.

Note: The offset might be negative.


Solution

  • Perhaps the answer is to use ptrdiff_t? It...

    • can be negative;
    • alludes to the difference not being in bytes, but in units of arbitrary size depending on the element type.

    What do you think?