#include <iostream>
using namespace std;
int main()
{
int i;
const char *arr[] = {"C", "C ", "Java", "VBA"};
const char *(*ptr)[4] = &arr;
cout << (*ptr)[2];
return 0;
}
Output is "ava"
I am not able to understand why code is giving this output. I tried to breakdown the code line by line to understand, but I am not that good in pointers so I am not able to understand what *(*ptr)[4] and (*ptr) is doing? So I want to know their functionality in this code
CodePudding user response:
Lets look at different statements in your program.
Case 1
Here we consider the statement:
const char *arr[] = {"C", "C ", "Java", "VBA"};
The above statement creates an array named arr
that contains elements of type const char*
. The size of this array is 4.
Case 2
Here we consider the statement:
const char *(*ptr)[4] = &arr;
The above statement creates a pointer named ptr
that points to an array of size 4 that contains elements of type const char*
. Moreover, this pointer ptr
is initialized with &arr
. This means, the pointer ptr
is pointing to the array arr
.
Since arr
is of type const char* [4]
therefore , &arr
gives us a const char* (*)[4]
.
Case 3
Here we consider the statement:
cout << (*ptr)[2];
In the above statement, (*ptr)
dereferences the pointer named ptr
. This gives us the object to which ptr
was pointing. But we know that(from case 2) ptr
is pointing to the array arr
. So the result of (*ptr)
is nothing but the array named arr
.
Now, the operator []
has higher precedence than operator
. This means that the array arr
that we got as a result of dereferencing, is subscripted for the value 2
. That is we now get the 3rd element(which is at index 2
) of the array arr
. This means we now have a pointer that is pointing to the first element/character of the string literal "Java"
.
Finally, that pointer value is incremented. This is because of the
. This mean now after incrementing, the pointer is pointing to the next character(which is 'a'
) in the string literal "Java"
.
So when you use cout
on this pointer you get ava
as the output because the pointer was pointing to the character 'a'
and not 'J'
.
CodePudding user response:
First line:
const char *(*ptr)[4] = &arr;
This declares
ptr
to be a pointer to an array of 4 pointers to const char, and initialize it to point toarr
second one (I willingly omitted the
cout
):(*ptr)[2];
This increments the third element of the array pointed to by
ptr
, hencearr
. After that, printing elements of the array would giveC
,C
,ava
andVBA
.