给定代码:
int arr[] = {11,22,33,44,55}
for(int i = 0; i <5 ; i++)
cout << *(arr+i) << " ";
*(arr+i)
和arr[i]
的效果一样吗?
最佳答案
是的。事实上,下标运算符 E1[E2]
被定义为等同于 *((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))
.
关于C++ 指针运算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16223375/