Re: Correct type for array indices

From: Bjørn Augestad (boa_at_metasystems.no)
Date: 11/27/04


Date: Sat, 27 Nov 2004 12:56:46 GMT

Christian Bau wrote:

> In article <pan.2004.11.27.06.44.59.446630@bel.bc.ca>,
> Sean Hamilton <sh@bel.bc.ca> wrote:
>
>
>>Hello,
>>
>>Suppose I have a pointer to some structures. What would be the correct
>>type to store the number of entries in that array, as well as for indexing
>>that array? size_t seems like an obvious choice, but off_t also jumps to
>>mind.
>
>
> Unsigned types like size_t always have the disadvantage that they behave
> in non-mathematical ways when you subtract 1 from 0.
>
> if (i > count-1)
>
> will give a complete nonsense result if count == 0. So you have to watch
> out constantly to get everything right.

Is that really a problem? I know that the code above is just an example,
but it could easily be written as
        if(i + 1 > count)
        if(i >= count)
and there would be no problem, as far as I can tell.

>
> Use int if the number of elements is less than 32767, use long if the
> number of elements is less than 2 billion.

Since functions/operators like sizeof/malloc/strlen/strspn and many,
many more all returns or expects a size_t, why not use it?

Bjørn



Relevant Pages

  • Re: A function returning string or pointer
    ... as a result from my previous post I'm busy with splitting code into ... a pointer to this array. ... You /must not/ return a pointer to an array which is a local ... You must return a pointer to store which will outlive the function ...
    (comp.lang.c)
  • Re: Correct type for array indices
    ... Sean Hamilton wrote: ... > Suppose I have a pointer to some structures. ... > type to store the number of entries in that array, ...
    (comp.lang.c)
  • Re: array of pointers
    ... > array of pointers is neccesary more RAM memory to store these datas. ... derived type has a pointer component. ... upper bound for each rank, although that is at least largely redundant. ...
    (comp.lang.fortran)
  • Re: My error or bug in "attr_reader" ?
    ... attr_reader:entries ... @entries isn't an array, it's a pointer to an instance of the ... A reference is just a pointer with slightly ...
    (comp.lang.ruby)
  • Re: [RFC] defer skb allocation in virtio_net -- mergable buff part
    ... have an array of pages per list element instead of just one pointer ... store an array of page pointers in one of the free ...
    (Linux-Kernel)

Loading