when I declare an array, a pointer is also created that points to the first element in the array and the name of the pointer is the same name of the array, |
When you declare the array (line 1 of your code), you have only created an array. It is not a pointer in itself, but implicitly decays into a pointer when used as such.
Your 'array' variable is not a pointer. It is, in fact, an array. 'array' is an array of 5 ints.
However, the decay happens when the array is used like a pointer, or passed into a function (by value), or dereferenced, which is to say almost every circumstance (but not all of them).
And if I am, what then happens if I create another pointer and assign the array to that pointer (like shown below) |
Assigning a pointer to another pointer does not make it a pointer to a pointer, it just copies the value of the pointer, which is the address it points to.
If we take arrays out of the equation, what we have is something like this:
1 2 3 4 5 6 7 8 9 10 11 12
|
#include <iostream>
int main()
{
int foo = 42;
int* pfoo = &foo;
int* another_pfoo = pfoo;
std::cout << (*pfoo) << '\n';
std::cout << (*another_pfoo) << '\n';
}
|
another_pfoo is still just a normal pointer, not a pointer to a pointer. To create a pointer to a pointer, you would need to take the address of an existing pointer variable.
1 2 3 4 5 6
|
int main()
{
int my_int = 100;
int* my_ptr = &my_int;
int** my_ptr_to_ptr = &my_ptr;
}
|
And then what is the point in assigning a pointer to an array |
You can't assign a pointer to an array. That would be a compiler error. Try it yourself (click on the gear symbol next to the code to run it in cpp.sh).
1 2 3 4 5 6 7 8 9
|
int main()
{
int array[5] {};
int some_data = 12345;
int* ptr = &some_data;
array = ptr;
}
|
main.cpp: In function ‘int main()’:
main.cpp:8:13: error: incompatible types in assignment of ‘int*’ to ‘int [5]’
array = ptr;
^~~ |
I assume you meant, why assign an array to a pointer? Indeed, it's not really necessary. It was probably just shown to you for demonstration purposes.
When you do
int* ptr = array;
the array decays into a pointer here, and what you're left with is a pointer to the first element of the array, and this pointer's value (the address) is copied into ptr.
Here is another notable difference between an array and a pointer.
1 2 3 4 5 6 7 8 9 10
|
#include <iostream>
int main()
{
int array[5] {};
int* ptr = array;
std::cout << sizeof(array) << '\n';
std::cout << sizeof(ptr) << '\n';
}
|
sizeof(array) most likely prints 20 for you. This is because array is an array of 5 ints, and sizeof(int) is most likely 4. So it's doing sizeof(int) * 5, or 4 * 5 = 20.
sizeof(ptr) is printing the size of an int-pointer on your system, which is most likely 8 if you're compiling as 64-bit.