The answer to the OP's question is yes, size_t is most appropriate for the example code, where no pointer values are being subtracted from each other, and there are no cross-compiler/library compatibility issues around malloc
behaviors. Regardless of difference in heap managers, in C, an array can be SIZE_MAX
bytes in length and that requires a size_t
to represent it. Nothing in the standard requires a heap manager to be able to allocate all of a process memory space in the heap, or to allocate up to SIZE_MAX
bytes for that matter, but an array can be SIZE_MAX
in length, hence size_t
is appropriate.
Even if n
is signed, using a ptrdiff_t
for i
isn't going to help, as the initial i < n
test will fail anyway, if n
is negative, because i
is initialized to zero. There is no index into i
that a size_t
index cannot access. The only place that ptrdiff_t
is needed, is where you subtract one pointer value from another, and the OP isn't asking about that.
ptrdiff_t
is a signed type, so it may not be very safe if you access array with. – Headshipn
is and whata
is. Ifa
is a built-in array,size_t
is more appropriate. – Gilesptrdiff_t
may actually be larger thansize_t
which would seem to make this less efficient and dangerous. – Vadimcontainer::size_type
is, but this question is on C, not C++.(Guessing that's C++?) – Vadimi
are >=0, so size_t is definitely more appropriate. – Cadefor(pntrdiff_t i = 0; i < n; i++)
that lacked a type for n. After reading the whole article it is clear that size_t is perfectly safe for all unsigned pointer arithmetic, but you should always use pntrdiff_t for anything that involves signed entities in the expression. Not the strongest article on the subject, I am sure, but I can't provide a better example at the moment. – Cade