C - Pointer Pointer Accessing

Introduction

You use the indirection operator, *, to access the value of the variable pointed to by a pointer.

This operator is referred to as the dereference operator.

int number = 15;
int *pointer = &number;
int result = 0;

The pointer variable contains the address of the variable number, you can use this in an expression to calculate a new value for result:

result = *pointer + 5;

*pointer will evaluate to the value stored at the address contained in the pointer.

This is the value stored in number, 15, so result will be set to 15 + 5, which is 20.

The following code declares a variable and a pointer and outputs their addresses and the values they contain.

Demo

#include <stdio.h>

int main(void)
{
  int number = 0;                 // A variable of type int initialized to 0
  int *pnumber = NULL;            // A pointer that can point to type int

  number = 10;/*from  w  w w  .  ja v a 2 s.c o  m*/
  printf("number's address: %p\n", &number);               // Output the address
  printf("number's value: %d\n\n", number);                // Output the value

  pnumber = &number;              // Store the address of number in pnumber

  printf("pnumber's address: %p\n", (void*)&pnumber);      // Output the address
  printf("pnumber's size: %zd bytes\n", sizeof(pnumber));  // Output the size
  printf("pnumber's value: %p\n", pnumber);                // Output the value (an address)
  printf("value pointed to: %d\n", *pnumber);              // Value at the address
  return 0;
}

Result

Related Topics

Example