If the expression type name[count]
is written in some function then you tell the C compiler to allocate on the stack frame sizeof(type)*count
bytes and compute the address of the first element in the array.
If the expression type name[count]
is written outside all functions and structs definitions then you tell the C compiler to allocate on the data segment sizeof(type)*count
bytes and compute the address of the first element in the array.
name
actually is constant object that stores the address of the first element in the array and every object that stores an address of some memory is called pointer, so this is the reason you treat name
as a pointer rather than an array. Note that arrays in C can be accessed only through pointers.
If count
is a constant expression that evaluates to zero then you tell the C compiler to allocate zero bytes either on the stack frame or data segment and return the address of the first element in the array, but the problem in doing this is that the first element of zero-length array doesn't exist and you cannot compute the address of something that doesn't exist.
This is rational that element no. count+1
doesn't exist in count
-length array, so this is the reason that the C compiler forbids to define zero-length array as variable in and outside of a function, because what is the contents of name
then? What address name
stores exactly?
If p
is a pointer then the expression p[n]
is equivalent to *(p + n)
Where the asterisk * in the right expression is dereference operation of pointer, which means access the memory pointed by p + n
or access the memory whose address is stored in p + n
, where p + n
is pointer expression, it takes the address of p
and adds to this address the number n
multiply the size of the type of the pointer p
.
Is it possible to add an address and a number?
Yes it is possible, because address is unsigned integer commonly represented in hexadecimal notation.
struct { int p[1],q[1]; } foo; int *pp = p+1;
,pp
would be a legitimate pointer, but*pp
would not have a unique address. Why could the same logic not hold with a zero-length array? Say that givenint q[0];
within a structure,q
would refer to an address whose validity would be like that of thep+1
example above.