Dereferencing Pointers - C Pointer

C examples for Pointer:Introduction

Introduction

The pointer contains the memory address to the variable.

Referencing the pointer will retrieve this address.

To obtain the actual value stored in that address, the pointer must be prefixed with an asterisk, known as the dereference operator (*).

Demo Code

#include <stdio.h>
int main(void) {
    int i = 10;/*from w  w  w  . j a v a 2 s .com*/
    int* p; /* pointer to an integer */
    p = &i; /* address of i assigned to p */
    printf("Address of i: %p \n", p); /* ex. 0017FF1C */
    printf("Value of i: %d",  *p); /* 10 */
}

Result

Without the asterisk the pointer is assigned a new memory address.

With the asterisk the actual value of the variable pointed to will be updated.

Demo Code

#include <stdio.h>
int main(void) {
    int i = 10;//from   w ww.  j a v  a2  s  .  co  m
    int* p; /* pointer to an integer */

    p = &i;  /* address of i assigned to p */
    *p = 20; /* value of i changed through p */
}

The following code shows how to get a copy of the first pointer's memory address.

Demo Code

#include <stdio.h>
int main(void) {
    int i = 10;/*from  w  w w. ja v  a2  s  .c o m*/
    int* p; /* pointer to an integer */

    p = &i;  /* address of i assigned to p */

    int* p2 = p; /* copy address stored in p */
}

Related Tutorials