So, I always knew that the array "objects" that are passed around in C/C++ just contained the address of the first object in the array.
How can the pointer to the array "object" and it's contained value be the same?
Could someone point me towards more information maybe about how all that works in assembly, maybe.
In C, it is possible to have array of all types except following. 1) void. 2) functions. But we can have array of void pointers and function pointers.
A void pointer(void* ) is a pointer that has no associated data type with it. A void pointer can hold address of any type and can be typcasted to any type.
You can't have a variable of type void (or an array of void ) for the simple reason that there are no values of type void for it to hold.
To create an array, define the data type (like int ) and specify the name of the array followed by square brackets []. To insert values to it, use a comma-separated list, inside curly braces: int myNumbers[] = {25, 50, 75, 100};
Short answer: A pointer to an array is defined to have the same value as a pointer to the first element of the array. That's how arrays in C and C++ work.
Pedantic answer:
C and C++ have rvalue and lvalue expressions. An lvalue is something to which the &
operator may be applied. They also have implicit conversions. An object may be converted to another type before being used. (For example, if you call sqrt( 9 )
then 9
is converted to double
because sqrt( int )
is not defined.)
An lvalue of array type implicitly converts to a pointer. The implicit conversion changes array
to &array[0]
. This may also be written out explicitly as static_cast< int * >( array )
, in C++.
Doing that is OK. Casting to void*
is another story. void*
is a bit ugly. And casting with the parentheses as (void*)array
is also ugly. So please, avoid (void*) a
in actual code.
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