How are array variables stored in C? (not the memory itself but the pointer in the named variable)
Arrays are stored like other objects: an int
, a struct
, etc. Each exists in memory, starting at some address*1 and occupying sizeof object
bytes.
An object, being an array or not, has an address. Each element of an array has an address.
are array variables stored as wide pointers?
No.
Why does sizeof fail when the array is passed to a function?
sizeof
does not fail. It is that when an array is passed to a function, it is first converted to the type and address of the first element. The function receives a pointer, not an array. The below prints the size of the array a
(e.g. 12) and then the size of the pointer ptr
(e.g. 2, 4, or 8). Expecting sizeof ptr
to be the size of an array is not a failure on the language's part.
int foo(int *ptr) {
printf("%zu\n", sizeof ptr);
return 0;
}
int main() {
int a[3] = { 1,2,3,};
printf("%zu\n", sizeof a);
return foo(a);
}
arrays in C are really confusing me.
Remembering that arrays are not pointers and pointers are not arrays is useful.
Is there a reason why you can't pass an array as an argument like in rust and why it always decays?
... because the C language is defined that way. It was deemed a good design at the time and given 40+ years of use, was at least a reasonable choice.
*1 An object stored in a register has no address.