Given the code:
int arr[] = {11,22,33,44,55}
for(int i = 0; i <5 ; i++)
cout << *(arr+i) << " ";
Does *(arr+i)
have the same effect as arr[i]
?
Given the code:
int arr[] = {11,22,33,44,55}
for(int i = 0; i <5 ; i++)
cout << *(arr+i) << " ";
Does *(arr+i)
have the same effect as arr[i]
?
Yes. In fact, the subscript operator E1[E2]
is defined as equivalent to *((E1)+(E2))
:
A postfix expression followed by an expression in square brackets is a postfix expression. One of the expressions shall have the type “pointer to
T
” and the other shall have unscoped enumeration or integral type. The result is an lvalue of type “T
.” The type “T
” shall be a completely-defined object type. The expressionE1[E2]
is identical (by definition) to*((E1)+(E2))
.
yes. array are decayed to pointers
. Array name points to first element of array. So
*(arr +i)
is equivalent to:
arr[i]