What is the correct type for array indexes in C?

24,227

Solution 1

Since the type of sizeof(array) (and malloc's argument) is size_t, and the array can't hold more elements than its size, it follows that size_t can be used for the array's index.

EDIT This analysis is for 0-based arrays, which is the common case. ptrdiff_t will work in any case, but it's a little strange for an index variable to have a pointer-difference type.

Solution 2

My choice: ptrdiff_t

Many have voted for ptrdiff_t, but some have said that it is strange to index using a pointer difference type. To me, it makes perfect sense: the array index is the difference from the origin pointer.

Some have also said that size_t is right because that is designed to hold the size. However, as some have commented: this is the size in bytes, and so can generally hold values several times greater than the maximum possible array index.

Solution 3

I usually use size_t for array offsets, but if you want negative array indexing, use int. It is able to address the maximum sized-array guaranteed by C89 (32767 bytes).

If you want to access arrays of the maximum size guaranteed by C99 (65535 bytes), use unsigned.

See previous revisions for accessing arrays allowed, but not guaranteed, by C.

Share:
24,227
Michas
Author by

Michas

Quite young Linux user and old school programmer. I program mostly for fun and personal development, in many languages. Sometimes for profit.

Updated on July 09, 2022

Comments

  • Michas
    Michas almost 2 years

    What type for array index in C99 should be used? It have to work on LP32, ILP32, ILP64, LP64, LLP64 and more. It doesn't have to be a C89 type.

    I have found 5 candidates:

    • size_t
    • ptrdiff_t
    • intptr_t / uintptr_t
    • int_fast*_t / uint_fast*_t
    • int_least*_t / uint_least*_t

    There is simple code to better illustrate problem. What is the best type for i and j in these two particular loops. If there is a good reason, two different types are fine too.

    for (i=0; i<imax; i++) {
            do_something(a[i]);
    }
    /* jmin can be less than 0 */
    for (j=jmin; j<jmax; j++) {
            do_something(a[j]);
    }
    

    P.S. In the first version of question I had forgotten about negative indexes.

    P.P.S. I am not going to write a C99 compiler. However any answer from a compiler programmer would be very valuable for me.

    Similar question: