DEV Community

EffessDev
EffessDev

Posted on

Dual role of * in C

Prerequisites

Let's create a variable.

int myNum = 5;
Enter fullscreen mode Exit fullscreen mode

Now, myNum refers to the value 5. However, we can get its memory address using the & operator like this: &myNum.

Role 1: Creating pointers

A pointer holds a memory address.

int *pointerToMyNum = &myNum;
Enter fullscreen mode Exit fullscreen mode

Role 2: Modifying values using a pointer

In this case, * works as the dereference operator.

*pointerToMyNum = 10;
Enter fullscreen mode Exit fullscreen mode

Now, if we print myNum, the output will be 10.

Understanding that they are different in each context makes things much easier ✨

Note

Both int ptr and int ptr are functionally identical in C.

Top comments (0)