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?
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?
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.
This is the number of elements (int
s 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]);
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.
Addition and substraction for pointers works in accordance to the pointer type.