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
",urn,&urn,&a);
    printf("pointer value, dereferenced pointer, pointer address:
");
    printf("ptr1 = %p, *ptr1 = %d, &ptr1 = %p
", ptr1, *ptr1, &ptr1);

    // pointer addition
    ptr3 = ptr1 + 4;
    printf("
adding an int to a pointer:
");
    printf("ptr1 + 4 = %p, *(ptr1 + 4) = %d
", ptr1 + 4, *(ptr1 +4));
    ptr1++; // increase
    printf("
values after ptr1++:
");
    printf("ptr1 = %p, *ptr1 = %d, &ptr1 = %p
", ptr1, *ptr1, &ptr1);
    ptr2--;  // decrease
    printf("
values after -ptr2:
");
    printf("ptr2 = %p, *ptr2 = %d, &ptr2 = %p
", ptr2, *ptr2, &ptr2);
    --ptr1;
    --ptr2;
    printf("
Pointers reset to original values:
");
    printf("ptr1 = %p, ptr2 = %p
", ptr1, ptr2);
    // ont pointer minus another pointer.
    printf("
subtracting one pointer from another:
");
    printf("ptr2 = %p, ptr1 = %p, ptr2 - ptr1 = %td
", ptr2, ptr1, ptr2 - ptr1);
    // ont pointer minus a integer.
    printf("
subtracting an int from a pointer:
");
    printf("ptr3 = %p, ptr3 - 2 = %p
", 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.

原文地址:https://www.cnblogs.com/enomothem/p/11923515.html