An array is notably not a pointer. To be sure, both lvalues seem to contain the (1-dimensional) coordinate of some position in (1-dimensional) virtual memory. But consider this example.
#include <stdlib.h>
#include <stdio.h>
int main(){
char buffer0[4096];
char* buffer1 = malloc(4096);
printf("lvalue %16p sizeof %lu\n", (void *) buffer0, sizeof(buffer0));
printf("lvalue %16p sizeof %lu\n", (void *) buffer1, sizeof(buffer1));
// Example output: lvalue 0x7ffcb70e8620 sizeof 4096
// Example output: lvalue 0x7a4420 sizeof 8
}
Practical differences that come to mind are:
- Arrays know how big (in bytes) they are (and, by extension, they know how many elements they have); pointers don't (but
malloc()
must know how big a pointer is, to know how much tofree()
given just the pointer...!) - Arrays are "garbage collected" (no need to
free()
them); pointers must be freed manually (if they own a non-trivial amount of memory, ie. throughmalloc()
) - Arrays "live" in the stack (high virtual memory addresses, at least on my platform); pointers "live" in the heap (low virtual memory addresses)
- Arrays decay to pointers when passed to functions
- Arrays cannot be resized; pointers can
Overall, arrays seem to be much smarter (but less versatile) than pointers (they know how big they are, how many elements they have, and they have automatic memory management).
Questions
- How do arrays "know" how big they are? How is this implemented?
- In general, how are arrays implemented in the C language? (Does the compiler do this, or does the kernel?