sizeof and array parameters

Craig Partridge craig at loki.ARPA
Fri Dec 28 06:13:35 AEST 1984


    I don't remember seeing this precise topic discussed,  if it
has, someone please enlighten me.

    I was trying to be overly fancy recently and wrote a function that
looked roughly like this (though somewhat more complex):

#define ARRAYSIZE 4

readarray(fd,a)
int fd;
int a[ARRAYSIZE];
{
    read(fd,a,sizeof(a));
}

It failed to work, because sizeof(a) was 4 (the size of a pointer)
instead of 16 (4 positions of ints of size 4).  (This is with the
Berkeley and SUN compilers).

    Now I know why sizeof(a) returned 4 --- "a" is actually a pointer to
int, and that is how it is represented in readarray, and indeed, I caught
this bug reasonably quickly.   However, the more I think about it, the
more I feel that sizeof should have returned 16.  K&R never
explicitly covers this issue, in section 7.2 all they say is that
sizeof an array yields the total number of bytes in the array.
The question of course, is whether one should view paramter "a" as
an array, or just a pointer.  My view is that it is an array, and
should be treated as such.

    My justification for this view is simply, that since it has a dimension
there is no justification for semantically treating "a" as if it were simply
a pointer to integer.  Obviously the representation is still a pointer
to integer, but the major justification for "int a[]" being equivalent
to "int *a" is simply that we don't know the true size of "a".  Since
we do know the size of the array "a" refers to (or think we do, and lint
could tell us if the sizes of the parameters actually passed were off),
why shouldn't sizeof reflect that information?

    Please respond to me directly, and I'll summarize.

Craig Partridge
craig at bbn-loki
{wjh12,decvax,ihnp4}!bbncca!craig



More information about the Comp.lang.c mailing list