Reputation: 567
In http://www.fredosaurus.com/notes-cpp/arrayptr/array-diagrams.html website, it states that
Pointers hold the memory address of other data and are represented by a black disk with an arrow pointing to the data it references.
For example,
int a[5]; // Allocates memory for 5 ints.
. . .
a[0] = 1;
for (int i=1; i<5; i++) {
a[i] = a[i-1] * 2;
}
My question is how can I print the address of the pointer pointing to the array?
I know that &a
or &a[0]
gives us the address of the first element. But how can I access the pointer pointing the array?
Upvotes: 2
Views: 2315
Reputation: 238361
I know that
&a
or&a[0]
gives us the address of the first element.
Technically. &a
is in fact the address of the array itself. It just has the same value as address of the first element. But note that the type of the expression is different. &a
is a int (*)[5]
(pointer to an array of 5 integers), while &a[0]
is a int*
(pointer to an integer).
My question is how can I print the address of the pointer pointing to the array?
First step is to have a pointer. You don't have any pointer variables in your example. An array is not a pointer. The sentence "The actual array variable, a in this example, is a pointer to the memory for all of its elements." of the page is very misleading, as an array is not a pointer object. The drawn diagram is not correct for the program.
Here is a program that is correct according to the diagram:
int array[5]; // Allocates memory for 5 ints.
int* a = array; // a pointer to the first element of the array
a[0] = 1;
for (int i=1; i<5; i++) {
a[i] = a[i-1] * 2;
}
Here we actually have a pointer. Now you can print the address of the pointer:
std::cout << &a;
Upvotes: 0
Reputation: 449
If the array is on the stack as it would be in your example code then the image below is a more accurate representation of how the memory would be laid out. I've also added an additional pointer to hopefully add some clarification.
int a[5];
a[0] = 1;
for (int i=1; i<5; i++)
a[i] = a[i-1] * 2;
int* b = a;
It may be easier to think of the []
notation of defining an array as a little syntactic sugar. When calling functions and passing in a
the function will be called with the address of a[0]
being passed in.
When passing b
to a function it's the value that will be passed in, which is the address of a
.
Upvotes: 1
Reputation: 224072
An array and a pointer are not the same thing. What the memory really looks like is this:
a
-------
| 1 | a[0]
-------
| 2 | a[1]
-------
| 4 | a[2]
-------
| 8 | a[3]
-------
| 16 | a[4]
-------
So if you were to print a
and &a
, you would see that they print the same value.
Upvotes: 1
Reputation: 22023
You can have lots of pointers pointing to a[0]
.
Just as for a pointer to the array, create a pointer variable pointing to a[0]
and then take a pointer to it. You will have one pointer to one pointer pointing to the array.
Upvotes: 0