C lang:Pointer operation

Xx_Pointer opteration

Do not dereference initialized Pointers

Ax_Code

#include<stdio.h>

int main(void)
{
    int urn[5] = { 100, 200, 300, 400, 500 };
    int * ptr1, *ptr2, *ptr3;
    int a =2;
    ptr1 = urn; // equal to &urn[0]
    ptr2 = &urn[2];
    printf("%p,%p,%p\n",urn,&urn,&a);
    printf("pointer value, dereferenced pointer, pointer address:\n");
    printf("ptr1 = %p, *ptr1 = %d, &ptr1 = %p\n", ptr1, *ptr1, &ptr1);

    // pointer addition
    ptr3 = ptr1 + 4;
    printf("\nadding an int to a pointer:\n");
    printf("ptr1 + 4 = %p, *(ptr1 + 4) = %d\n", ptr1 + 4, *(ptr1 +4));
    ptr1++; // increase
    printf("\nvalues after ptr1++:\n");
    printf("ptr1 = %p, *ptr1 = %d, &ptr1 = %p\n", ptr1, *ptr1, &ptr1);
    ptr2--;  // decrease
    printf("\nvalues after -ptr2:\n");
    printf("ptr2 = %p, *ptr2 = %d, &ptr2 = %p\n", ptr2, *ptr2, &ptr2);
    --ptr1;
    --ptr2;
    printf("\nPointers reset to original values:\n");
    printf("ptr1 = %p, ptr2 = %p\n", ptr1, ptr2);
    // ont pointer minus another pointer.
    printf("\nsubtracting one pointer from another:\n");
    printf("ptr2 = %p, ptr1 = %p, ptr2 - ptr1 = %td\n", ptr2, ptr1, ptr2 - ptr1);
    // ont pointer minus a integer.
    printf("\nsubtracting an int from a pointer:\n");
    printf("ptr3 = %p, ptr3 - 2 = %p\n", ptr3, ptr3 - 2);

    return 0;
}



Assign: assign a pointer to a pointer.It can be the name of an array, the name of an address variable, or a pointer

The dereference: * operator gives the pointer to the value stored at the address.(this is the pointer.)

Address: like all variables, a pointer variable has its own address and reference, & itself.Store the address to memory.

Pointer plus integer: the integer is multiplied by the size of the pointing type (int is 4) and then added to the initial address.(you can't go beyond the array, but you can reasonably go

beyond it.Right at the end of the first position, which is allowed.)

Incrementing pointer: incrementing a pointer to an array element can move the pointer to the next element in the array.If int = + 4 (because int = 4, double = 8)

Pointer minus an integer: the pointer must be the first operand that integer is multiplied by the size of the pointing type and then subtracted by the initial value.

Decrement pointer: you can increment or decrement.

Difference of pointer: the difference of pointer can be calculated (this difference is the number of types, the distance in the same array).

Comparison: two Pointers of the same type are compared using the relational operator.

猜你喜欢

转载自www.cnblogs.com/enomothem/p/11923515.html