Is there any difference between &a[i] and a+i, where a is int*?
int*. The question is whether they are performed in the same way, since there are two operators in
&a[i] but only one operator in
In C, they are identical. The C standard defines
a[i]to be the same as
*(a + i), so
&*(a + i)which is
a + i. (The surprising consequence of this is that you could just as easily write
The number of operators has no real significance here.
Historically, technically, given
&aused to be technically invalid because it dereferenced a pointer past the end of an array, whereas
a+10has always been valid.
a[i]is defined as
ais an array or a pointer, and
iis an integer, then yes, that is equivalent to
a+i. When both
*are applied to the same pointer expression, they are now specifically specified to have no effect.
More details for those interested in the history: this is the text that was added in C99.
184.108.40.206 Address and indirection operators
3 [...] If the operand is the result of a unary
*operator, neither that operator nor the
&operator is evaluated and the result is as if both were omitted, except that the constraints on the operators still apply and the result is not an lvalue.
This text was not there yet in C89/C90, so the rule that a pointer subjected to the
*operator has to actually point to an object or function still technically applied. The standard was changed specifically to make such constructs valid.
I think both does the same job while your program runs because the compiler will general same set of instructions for both syntax’s.
For more information compile your program with options
-save-temps. Then see the assembly instructions in .s file. If both are same then it’s just the different syntax.