#include<iostream>
int num[3]={66,77,88};
int main()
{
int(*pi)[3]=#
std::cout<<*pi;
}
The result is an address instead of an array. What is the explanation behind this?
Pointer to an array points to an array, so on dereferencing it, we should get the array, and the name of array denotes the base address. So whenever a pointer to an array is dereferenced, we get the base address of the array to which it points.
An array name is not itself a pointer, but decays into a pointer to the first element of the array in most contexts. It's that way because the language defines it that way.
A user creates a pointer for storing the address of any given array. A user creates an array of pointers that basically acts as an array of multiple pointer variables. It is alternatively known as an array pointer. These are alternatively known as pointer arrays.
An array is represented by a variable that is associated with the address of its first storage location. A pointer is also the address of a storage location with a defined type, so D permits the use of the array [ ] index notation with both pointer variables and array variables.
not the entire array object?
*pi
gives the array, i.e. the int[3]
. But operator<<
for std::basic_ostream
doesn't have overloads taking array but has an overload taking pointer (const void*
), then array-to-pointer decay happens, the converted pointer (int*
) is pointing to the 1st element of the array and then is converted to const void*
, then is passed to std::cout
and gets printed out.
There is an implicit conversion from lvalues and rvalues of array type to rvalues of pointer type: it constructs a pointer to the first element of an array. This conversion is used whenever arrays appear in context where arrays are not expected, but pointers are:
Just like cout cannot print a vector, it cannot print an array. However cout will print the address of the first element.
If you take a look at the source code of iostream they mention cout as a pointer https://code.woboq.org/llvm/libcxx/src/iostream.cpp.html, and that is also why you always need to iterate over each item of your array as oppose to other languages (like Rust) where you can print a vector or an array.
For string there is an exception since in C and C++ they are (or should be!) NULL terminated, and that is why the whole char array is printed. But 0 is a valid number, hence there is no way to know the bounds of an int array unless you can detect it at compile time (which Rust does).
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