I have an array
int ar[5] = {1,2,3,4,5};
printf("%d",(ar==&ar));
The print statement returns true. But what if I do ar+1
and &ar+1
. Where does that point to?
Also if I have
char *c[] = {"GeksQuiz", "MCQ", "TEST", "QUIZ"};
char **cp[] = {c+3, c+2, c+1, c};
char ***cpp = cp;
where does cpp+1 point to? Is it after cp
i.e. cp[4]
or does it point to cp[1]
?
The address of an array corresponds to the location of the array object in memory, and has type "pointer to array". This location has the same value as the address of the first element of the array. The address of the first element of the array is what an array name will decay into when used in an expression. This explains why ar == &ar
.
Now, as ar
decays to the address of the first element, the ar + 1
is the address of the second element of the array. However, the value of &ar
has type pointer to an array, and so &ar + 1
actually points after the ar
array itself, which would be address of the object just past its last element (or &ar[5]
).
Your c
, cp
, and cpp
arrays can be pictorially represented like this:
"GeksQuiz" "MCQ" "TEST" "QUIZ"
^ ^ ^ ^
c: | | | |
+---+ | | | |
+-------->| *----+ | | |
| +---+ | | |
| +------>| *--------------------+ | |
| | +---+ | |
| | +---->| *-----------------------------+ |
| | | +---+ |
| | | +-->| *------------------------------------------+
| | | | +---+
| | | |
| | | | cp:
| | | | +---+
| | | +-----* |<--+
| | | +---+ |
| | +-------* | |
| | +---+ |
| +---------* | |
| +---+ |
+-----------* | |
+---+ |
|
|
+---+ |
cpp:| *-----+
+---+
Since cpp
is a pointer variable, cpp+1
is 1 greater than the value of that variable. The cpp
variable contains the decayed value of cp
(the address of its first element). So cpp+1
is the same as cp+1
, which would correspond to &cp[1]
, or the address of the second element of cp
.