Nearby lessons

54 of 72

C - Dereferencing a Pointer

Learn how to use the * operator to read or change the value stored at the address held by a pointer.

Reading a Value Using a Pointer

When a pointer stores the address of a variable, *ptr gives the value at that address. This is called dereferencing.

Example01
CCode Cell
1#include <stdio.h>
2 
3int main()
4{
5 int number = 10;
6 int *ptr = &number;
7 
8 printf("number = %d\n", number);
9 printf("*ptr = %d\n", *ptr);
10 
11 return 0;
12}
Output
number = 10
*ptr = 10

Changing a Value Using a Pointer

You can assign a new value to *ptr. This changes the original variable because the pointer refers to its address.

Example02
CCode Cell
1#include <stdio.h>
2 
3int main()
4{
5 int number = 10;
6 int *ptr = &number;
7 
8 printf("Before: %d\n", number);
9 
10 *ptr = 50;
11 
12 printf("After: %d\n", number);
13 
14 return 0;
15}
Output
Before: 10
After: 50

Remember the Difference

  • &number means the address of number.
  • ptr stores that address.
  • *ptr means the value at that address.
📝 Key Takeaways
  • The & operator gets an address.
  • The * operator accesses the value at a pointer address.
  • Changing *ptr can change the original variable.

🧠 Test Your Knowledge

2 Questions
Progress: 0 / 2