2

Possible Duplicate:
Pointer Arithmetic In C

Code:

int main() 
{ 
    int a[ ] ={0,1,2,3,4}; 
    char c[ ] = {'s','a','n','j','u'}; 
    printf("%d\n",&a[3]-&a[0]); 
    printf("%d\n",&c[3]-&c[0]); 
    return 0; 
}

Why the output comes 3 3 for both, if we consider the difference in addresses they will be different for both??

Community
  • 1
  • 1
Luv
  • 5,381
  • 9
  • 48
  • 61

1 Answers1

4

In pointer arithmetics, subtraction return the difference not in bytes, but in the pointer's type between two pointers.

So, since the difference in ints between a[3] and a[0] is identical to the difference in chars between c[3] and c[0] - you get the same result for both.

The arithmetics for pointers subtraction operation is something like:

type* p1 = ...
type* p2 = ...
p1 - p2 == (((int)p1) - (int(p2))) / sizeof(type)
amit
  • 175,853
  • 27
  • 231
  • 333