C - Get the value stored in memory via pointer

Introduction

The pointer can peek into that address and determine the value that's stored there.

The * operator is prefixed to the pointer's variable name.

A pointer variable contains a memory location.

The *pointer variable peeks into the value stored at that memory location.

Demo

#include <stdio.h>

int main()//from  ww  w  .  j a va 2  s  .  c o m
{
  char my_char;
  char *char_pointer;

  my_char = 'A';         /* initialize char variable */
  char_pointer = &my_char;   /* intialize pointer - IMPORTANT! */

  printf("About variable 'my_char':\n");
  printf("Size\t\t%u\n", sizeof(my_char));
  printf("Contents\t%c\n", my_char);
  printf("Location\t%p\n", &my_char);
  printf("And variable 'char_pointer':\n");
  printf("Contents\t%p\n", char_pointer);
  printf("Peek value\t%c\n", *char_pointer);

  return(0);
}

Result

When you specify the * before an initialized pointer variable's name, the results are the contents of the address.

The value is interpreted based on the type of pointer.

In this example, *char_pointer represents the char value stored at a memory location kept in the char_pointer variable, which is really the same as the memory location variable my_char.

Related Topic