Reputation: 229
I have an array a[2][2]
. Now it can be considered as consisting of two 1d arrays, a[0]
and a[1]
. Now as the name of an array points to the first element in an array, so a[0]
is the address of a[0][0]
i.e. a[0] = &a[0][0]
. Also a = &a[0]
according to the definition. So, combining the two a = &(&a[0][0])
; but when I print a it gives the address of a[0][0]
only i.e. &a[0][0]
. Why is that?
Upvotes: 1
Views: 149
Reputation: 3069
You cannot access the address of an address.
Address-of operator &
, can be used only for variables. What is a variable? For example, a
in int a;
would be a variable, it would be a variable that holds an integer value. Or b
in int * b
would also be a variable, a variable that holds an address, to which the ones who have created all these languages decided to refer as pointers. Same thing for c
in int c[10];
, except that c
there would be a constant variable, so you wouldn't be able to vary it; still, however, would be able to get the address of.
You can obtain the address of a variable because it is some data stored in some memory location for you. It has a definite place in memory; it does make sense to be able to know the address of a variable.
It doesn't make sense to know the address of an address. An address is just a number. Unlike a pointer, which -as I said- is a variable that holds an address, it doesn't have a definite place in memory for you to know of. It is just a number, so trying to take the address of an address as in &(&a);
, makes just as much sense as trying to take the address of number 4 as in &4
out of the blue.
As for the fact that each of &a
and &a[0]
and &a[0][0]
from your example yielding the same result; it is true that all of those three variables start off from the same memory location. However, they are not identical, they have this important difference:
&a[0][0]
is the address of an integer.&a[0]
is the address of an array of 2 integers.&a
is the address of an array of 2 arrays of 2 integers.So what they point at in the memory is different, like this:
// I'll use char so the bit-representation won't take long
char a[2][2] = {
{ 1, 2 },
{ 3, 4 }
};
/*
&a is the address of this whole thing:
0000 0001 0000 0010 0000 0011 0000 0100 .... ....
^ &a here ^ &a + 1 here
&a[0] is the address of this whole thing:
0000 0001 0000 0010 .... ....
^ &a[0] here ^ &a[0] + 1 here
&a[0][0] is the address of just this:
0000 0001 .... ....
^ &a[0][0] ^ &a[0][0] + 1
*/
So, what I'm trying to say is, they will differ when it comes to adding and subtracting numbers to and from them, and this is what they call as the pointer arithmetic.
Upvotes: 2