C arrays: some oddities
utzoo!decvax!ucbvax!menlo70!sri-unix!dan at BBN-UNIX
utzoo!decvax!ucbvax!menlo70!sri-unix!dan at BBN-UNIX
Sun Jan 3 23:30:32 AEST 1982
From: Dan Franklin <dan at BBN-UNIX>
The recent correspondence on the subject of arrays in C spurred me into
investigating them a little closer. In particular, while "array", "&array",
"&array[0]", "&array[0][0]", and so on, all had the same value, I wondered
whether their types differed--whether they were pointers to objects of
different sizes, as revealed by attempts to do arithmetic on them. So I wrote a
small program which declared a one-dimensional and a two-dimensional array, and
tried adding 1 to all those forms. I found the results surprising. Here is the
program's output, first as compiled with all the PDP-11 (Ritchie) compilers I
could find and then with the 4.1BSD (Johnson) compiler:
--------------------------- PDP-11 compilers -----------------------------------
char array1[10]
array1 = 4050 &array1 = 4050 &array1[0] = 4050
array1+1 = 4051 &array1+1 = 4060 &array1[0]+1 = 4051
char array2[10][3]
array2 = 4060 &array2 = 4060 &array2[0] = 4060 &array2[0][0] = 4060
array2+1 = 4063 &array2+1 = 4090 &array2[0]+1 = 4063 &array2[0][0]+1 = 4061
---------------------------- VAX ---------------------------------------------
char array1[10]
array1 = 6776 &array1 = 6776 &array1[0] = 6776
array1+1 = 6777 &array1+1 = 6777 &array1[0]+1 = 6777
char array2[10][3]
array2 = 6788 &array2 = 6788 &array2[0] = 6788 &array2[0][0] = 6788
array2+1 = 6791 &array2+1 = 6791 &array2[0]+1 = 6789 &array2[0][0]+1 = 6789
So with the Ritchie compilers, "array" is equivalent to "&array[0]" (even for
multidimensional arrays), while "&array" is a pointer to the array itself--
usually not a very useful thing to have. The portable C compiler, on the other
hand, makes "array" equivalent to "&array" and "&array[0]" on one-dimensional
arrays, but multidimensional arrays are more obscure: "&array[0]" is like
"&array[0][0]", which implies that the compiler tacks on an extra "[0]"
whenever it can. I find that pretty disturbing, since I would have expected
"&array2[0]+1" to get me the second row of three chars.
Conclusion: when lint says "& before array or function: ignored" it should be
read as "& beore array or function: watch out!"
More information about the Comp.unix.wizards
mailing list