简体   繁体   中英

C Pointer Arithmetic Efficiency

I've seen the explanations for pointer arithmetic (eg. Pointer Arithmetic ). But I was wondering is there a real difference between:
Given:

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

Does:

&(arr[1])

And:

arr + 1

Differ in any way, beside syntax. Is either technically more efficient? Is there certain context to use pointer addiction over the first? I saw the one example from Printing 1 to 1000 without loop or conditionals . Thanks in advance.

&arr[1] and arr + 1 (and &1[arr] !) are identical, and all compute the same pointer. Per the C standard, §6.5.3.2 :

The unary & operator yields the address of its operand....

...if the operand is the result of a [] operator, neither the & operator nor the unary * that is implied by the [] is evaluated and the result is as if the & operator were removed and the [] operator were changed to a + operator.

Thus, per the specification, &arr[1] is to be evaluated as if it were written arr + 1 .

Use of one over the other often comes down to preference. Personally, I like to use &arr[x] when I want to mean a pointer to just that element, and arr + x when I want to refer to an array starting at x .

No, there's no difference, not even in performance (unless we're talking about compile times) because:

  • arr[1] is equivalent to *(arr + 1) and
  • in &(*(arr + 1)) neither the dereference nor the address operators do anything (the C standard says explicitly, the dereference doesn't occur in such cases), so the operators cancel each other out.

So, after the parsing and the AST building phases the compiler eventually ends up with just arr + 1 in both cases.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM