Select Page

Dereferencing a Pointer (Indirection operator *)

by 05.03.2023C pointers

Using the indirection operator * is called dereferencing. It returns the value pointed to by a pointer variable.

#include <stdio.h>

int main(void)
{
	int	number;
	int	*ptr;

	number = 100;
	ptr = &number;
	printf("Address of ptr: %p, Value of number %i\n", ptr, number);
	printf("Value pointed to by a pointer variable ptr: %d, Value of number %i\n", *ptr, number);
	return (0);
}

In the following block, you can see what shows the terminal after compiling and executing:

Terminal> gcc main2.c
Terminal> ./a.out
Address of ptr: 0x7ffcfde31a6c, Value of number 100
Value pointed to by a pointer variable ptr: 100, Value of number 100

What means * and what means &?

  & Provides the address of something stored in memory.
  * Instructs the compiler to go to a location in memory.

Pointer pointing at some value in the memory

Let’s see the visualization of the 4th line in the following block of code:

	int	number;
	int	*ptr;

	number = 100;
	ptr = &number;

In the line ptr = &number;, we say to a pointer variable ptr to point to the address where the variable number is stored in memory.

Now let’s add another two lines of code:

	*ptr = 5;
	printf("%d", number);

With *ptr = 5, we go to the memory where pointer variable ptr points to and we assign the value 5 to whatever variable the pointer points to. As in our case pointer variable ptr points to the address where variable number is located, we change the value of variable number to 5.

By following line “printf(“%d”, number);”, the number 5 will be printed in Terminal.

[1] Understanding and Using C Pointers by Richard Reese (O’Reilly). Copyright 2013 Richard Reese, Ph.D. 978-1-449-34418-4
[2] Lecture 4: CS50x 2022. CS50x 2022 [online]. 2022 [cit. 2023-03-05]. Available at: https://cs50.harvard.edu/x/2022/notes/4/