Accessing a Value Through a Pointer - C Pointer

C examples for Pointer:Introduction

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.

Suppose you declare the following variables:

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

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

result = *pointer + 5;

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

result will be set to 15 + 5, which is 20.

The following program declares a variable and a pointer and then output their addresses and the values they contain.

Demo Code

#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;/* www.  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 Tutorials