How exactly pointer subtraction works in case of integer array?

前端 未结 4 551
自闭症患者
自闭症患者 2020-12-17 05:51
#include
int main()
{
    int arr[] = {10, 20, 30, 40, 50, 60};
    int *ptr1 = arr;
    int *ptr2 = arr + 5;
    printf(\"Number of elements between          


        
4条回答
  •  抹茶落季
    2020-12-17 06:22

    Pointer arithmetics is always in the units of the base type.

    In your case you have

    int *ptr1 = ...
    

    Then doing ptr1 + 5 will add sizeof(*ptr1) * 5 bytes to the pointer ptr1. Considering that sizeof(*ptr1) (which is the same as sizeof(int)) is 4, then you get 4 * 5 which equals 20 bytes.

提交回复
热议问题