-1

Possible Duplicate:
Pointer Arithmetic

The given code

int arr[12];
int * cur = arr;
cur++;
cout<<"cur-arr = "<<cur-arr<<endl;

Outputs 1, but I expected sizeof(int). Can someone please explain the nature of this behavior?

Community
  • 1
  • 1
Kunal
  • 511
  • 2
  • 6
  • 12

4 Answers4

4

It's a defined behavior of C pointer arithmetic. It uses the size of pointed type as a unit. If you change subtraction in the last line to

(char *)cur - (char *)arr 

you get 4 in the output.

Alex
  • 51
  • 3
3

This is the number of elements (ints here) between arr and cur (which is arr+1 at the time of subtraction). Compiler takes note that cur is a pointer to an integer and arr is an integer array. To get total number of bytes, try this:

(cur - arr) * sizeof(arr[0]);
Donotalo
  • 12,748
  • 25
  • 83
  • 121
2

cur is a pointer to int, initialized to some value (arr - the semantics of array-to-pointer conversion are irrelevant here), incremented (cur++) and compared to its old value. Unsurprisingly, it grew by one through the increment operation.

Pointer arithmetic with a given type works just like regular arithmetic. While the pointer is advanced by sizeof(int) bytes in this example, the difference between pointers is also calculated in units of sizeof(int), so you see plain simple arithmetics.

thiton
  • 35,651
  • 4
  • 70
  • 100
  • That's not quite *incrementing*, the pointer itself grew not by one. It grew by `sizeof(int)`, but the pointer substraction operator returns difference in **elements**, not in bytes. – ulidtko Jan 04 '12 at 17:01
  • @ulidtko: It doesn't really matter. When you take the abstraction into account, it's certainly an increment, even though the underlying value increases by more than `(int)1`. – Lightness Races in Orbit Jan 04 '12 at 17:07
1

Addition and substraction for pointers works in accordance to the pointer type.

Alex
  • 9,891
  • 11
  • 53
  • 87