【C语言学习笔记】指针的“加减”运算

例子1:

#include <stdio.h>
 
int main()
{
    float arr[5] = {12.5, 10.0, 13.5, 90.5, 0.5};
    float *ptr1 = &arr[0]; // ptr1 is 925601136
    float *ptr2 = ptr1 + 3;// ptr2 is 925601148
 
    printf("%f ", *ptr2);//90.500000
    printf("%d", ptr2 – ptr1); //ptr2 - ptr1 is 3
 
   return 0;
}

解释:

When we add a value x to a pointer p, the value of the resultant expression isp + x*sizeof(*p) where sizeof(*p) means size of data type pointed by p. That is why ptr2 is incremented to point to arr[3] in the above code.Same rule applies for subtraction. Note that only integral values can be added or subtracted from a pointer. We can also subtract or compare two pointers of same type.


例子2:

int main()
{
    int arr[] = {10, 20, 30, 40, 50, 60};
    int *ptr1 = arr;
    int *ptr2 = arr + 5;
    printf("Number of elements between two pointer are: %d.", (ptr2 - ptr1)); //5
    printf("Number of bytes between two pointers are: %d", (char*)ptr2 - (char*) ptr1); //20
    return 0;
}

解释:

Array name gives the address of first element in array. So when we do '*ptr1 = arr;', ptr1 starts holding the address of element 10. 'arr + 5' gives the address of 6th element as arithmetic is done using pointers. So 'ptr2-ptr1' gives 5. When we do '(char *)ptr2', ptr2 is type-casted to char pointer and size of character is one byte, pointer arithmetic happens considering character pointers. So we get 5*sizeof(int)/sizeof(char) as a difference of two pointers.

你可能感兴趣的:(【C语言学习笔记】指针的“加减”运算)