All,
This has been bugging me for a while now. In C\C++( i guess java and .NET as well) we do not ha开发者_JAVA百科ve to specify the row index in a multi-dimensional array. So, for example i can declare an array of ints as such:
int Array[][100];
I think static arrays in general are represented as contiguous memory on the stack. So, taking a column-major representation, how does the compiler know how much memory to allocate in the above case as it's missing one of the dimensions?
In C++ language you can't just do
int Array[][100]; /* ERROR: incomplete type */
because that would be a definition of an object of incomplete type, which is explicitly illegal in C++. You can use that in a non-defining declaration
extern int Array[][100];
(or as a static member of a class), but when it will come to the actual definition of the same array object both sizes will have to be specified explicitly (or derived from an explicit initializer).
In C the situation is not much different, except that in C there are such things as tentative definitions which let you write
int Array[][100];
However, a tentative definition in this regard is pretty similar to a non-defining declaration, which is why it is allowed. Eventually you will have to define the same object with explicitly specified size in the same translation unit (some compilers don't require that as an non-stanard extension). If you try something like that in a non-tentative definition, you'll get an error
static int Array[][100]; /* ERROR: incomplete type */
So, if you think of it, aside from tentative definitions, the situation in C and C++ is not much different: it is illegal to define objects of incomplete type in these languages and an array of unspecified size is an incomplete type.
In java and .NET, don't think about "the stack" -- objects live on the heap. And in C, that's just a declaration -- only a definition actually reserves memory! So that would NOT be an acceptable definition -- if you put it as the only line in file a.c
:
$ gcc -c a.c
a.c:1: warning: array ‘Array’ assumed to have one element
so gcc is just treating it as if it were int Array[1][100];
, as it warns you it's doing.
It does not know how much memory to allocate, what he knows with array[]
is that array is a pointer (like int *array
). array[][100]
( someone please correct me if i am wrong ) is the same as array[100]
.
精彩评论