Basic operations that can be performed with pointer variables. - C Pointer

C examples for Pointer:Pointer Variable

Description

Basic operations that can be performed with pointer variables.

Demo Code

#include <stdio.h>
int main(void)
{
    int urn[5] = {100,200,300,400,500};
    int * pointer1, * pointer2, *pointer3;
    /* w  w w. j av a  2  s .  c  o m*/
    pointer1 = urn;         // assign an address to a pointer
    pointer2 = &urn[2];     // ditto

    printf("pointer value, dereferenced pointer, pointer address:\n");
    printf("pointer1 = %p, *pointer1 =%d, &pointer1 = %p\n", pointer1, *pointer1, &pointer1);
    
    // pointer addition
    pointer3 = pointer1 + 4;
    printf("\nadding an int to a pointer:\n");
    printf("pointer1 + 4 = %p, *(pointer4 + 3) = %d\n", pointer1 + 4, *(pointer1 + 3));

    pointer1++;            // increment a pointer
    printf("\nvalues after pointer1++:\n");
    printf("pointer1 = %p, *pointer1 =%d, &pointer1 = %p\n", pointer1, *pointer1, &pointer1);

    pointer2--;            // decrement a pointer
    printf("\nvalues after --pointer2:\n");
    printf("pointer2 = %p, *pointer2 = %d, &pointer2 = %p\n", pointer2, *pointer2, &pointer2);

    --pointer1;            // restore to original value
    ++pointer2;            // restore to original value

    printf("\nPointers reset to original values:\n");
    printf("pointer1 = %p, pointer2 = %p\n", pointer1, pointer2);

    // subtract one pointer from another
    printf("\nsubtracting one pointer from another:\n");
    printf("pointer2 = %p, pointer1 = %p, pointer2 - pointer1 = %td\n", pointer2, pointer1, pointer2 - pointer1);

    // subtract an integer from a pointer
    printf("\nsubtracting an int from a pointer:\n");
    printf("pointer3 = %p, pointer3 - 2 = %p\n", pointer3,  pointer3 - 2);
    
    return 0;
}

Result


Related Tutorials