C Arithmetic pointer efficiency

I saw explanations for pointer arithmetic (e.g. Pointer arithmetic ). But I was wondering if there is a real difference between:
Considering:

int* arr = (int*) malloc(sizeof(int) * 3); 

whether:

 &(arr[1]) 

and

 arr + 1 

In any case, different from the syntax. Is it technically more efficient? Is there a specific context for using a pointer dependency over the first? I saw one example from Printing 1 to 1000 without a loop or legend . Thanks in advance.

+4
source share
2 answers

No, there is no difference, even in performance (if we are not talking about compilation time), because:

  • arr[1] equivalent to *(arr + 1) and
  • in &(*(arr + 1)) neither dereferencing nor the address operator do anything (the C standard explicitly states the difference does not occur in such cases), so the operators cancel each other out.

So, after the dismantling and phases of the AST building, the compiler ultimately ends only with arr + 1 in both cases.

+1
source

&arr[1] and arr + 1 (and &1[arr] !) are identical, and everyone computes the same pointer. According to standard C, Β§6.5.3.2 :

Unary and the operator gives the address of its operand ....

... if the operand is the result of the operator [], neither the operator nor the unary *, which is implied by [], are evaluated, and the result looks as if the operator had been deleted and [] the operator was replaced by the + operator.

Thus, for the specification &arr[1] it should be evaluated as if it were written by arr + 1 .

Using one over the other often comes down to preference. Personally, I like to use &arr[x] when I want to point to this element and arr + x when I want to refer to an array starting with x .

+5
source

All Articles