Search code examples
cpointershashtableptrdiff-t

Should I cast size_t to ptrdiff_t?


I have a malloc'ed array of pointers that forms a hash table. To step through the hash table I'd use pointer arithmetic, eg:

node_t ** tc = table;
size_t tcs = sizeof(node_t *);
for(long i = 0; i < tableSize; tc+=tcs, ++i) { 
    // Do some stuff with *tcs location in the table.
}

Question is should I cast the size_t returned by sizeof() to ptrdiff_t for correct addition in the increment part of the for condition? or does it even matter for addition?


Solution

  • No need for ptrdiff_t here as there is no pointer difference around.

    What you probably want is:

    for (node_t ** tc = table; tc < (table + tableSize); ++tc) {
      ...
    }