I know that an array decays to a pointer, such that if one declared
char things[8];
and then later on used things
somewhere else, things
is a pointer to the first element in the array.
Also, from my understanding, if one declares
char moreThings[8][8];
then moreThings
is not of type pointer to char but of type "array of pointers to char," because the decay only occurs once.
When moreThings
is passed to a function (say with prototype void doThings(char thingsGoHere[8][8])
what is actually going on with the stack?
If moreThings
is not of pointer type, then is this really still a pass-by-reference? I guess I always thought that moreThings
still represented the base address of the multidimensional array. What if doThings
took input thingsGoHere
and itself passed it to another function?
Is the rule pretty much that unless one specifies an array input as const
then the array will always be modifiable?
I know that the type checking stuff only happens at compile time, but I'm still confused about what technically counts as a pass by reference (i.e. is it only when arguments of type pointer are passed, or would array of pointers be a pass-by-reference as well?)
Sorry to be a little all over the place with this question, but because of my difficulty in understanding this it is hard to articulate a precise inquiry.
You got it slightly wrong: moreThings
also decays to a pointer to the first element, but since it is an array of an array of chars, the first element is an "array of 8 chars". So the decayed pointer is of this type:
char (*p)[8] = moreThings;
The value of the pointer is of course the same as the value of &moreThings[0][0]
, i.e. of the first element of the first element, and also the same of &a
, but the type is a different one in each case.
Here's an example if char a[N][3]
:
+===========================+===========================+====
|+--------+--------+-------+|+--------+--------+-------+|
|| a[0,0] | a[0,1] | a[0,2]||| a[1,0] | a[1,1] | a[1,2]|| ...
|+--------+--------+-------+++--------+--------+-------++ ...
| a[0] | a[1] |
+===========================+===========================+====
a
^^^
||+-- &a[0,0]
|+-----&a[0]
+-------&a
&a
: address of the entire array of arrays of chars, which is a char[N][3]
&a[0]
, same as a
: address of the first element, which is itself a char[3]
&a[0][0]
: address of the first element of the first element, which is a char
This demonstrates that different objects may have the same address, but if two objects have the same address and the same type, then they are the same object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With