Why cannot I find the element size via this pointer hack? [duplicate]

  • A+

This question already has an answer here:

Consider the following in C

int arr[]= {1,2,3,4,5}; 

My system uses 4 bytes to store int data. Now &arr[0] => 0022FEB0 and &arr[1]=>0022FEB4 at a moment of run


int diff=&arr[1]-&arr[0]; 

Value stored in diff is 1 and not 4.



That's the way pointers work. You are not calculating the byte difference. You're calculating the difference in number of elements.

To get the element size, use sizeof(*arr)

To get the byte difference, use (&arr[1]-&arr[0]) * sizeof(*arr)


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: