C - Dereference operator
The dereference operator (*
) in C is used to access the value stored at a particular memory address, typically through a pointer. It is essential for working with pointers and dynamic memory.
Learning Objectives
- Use
*
to read and write through pointers. - Avoid undefined behavior by checking pointer validity.
Prerequisites
What is the Dereference Operator?
The dereference operator (*
) allows you to access or modify the value pointed to by a pointer variable.
Syntax
*pointer_variable
Simple Example
#include <stdio.h>
int main(void) {
int x = 20;
int *ptr = &x;
printf("Value of x: %d\n", x);
printf("Value via pointer: %d\n", *ptr);
return 0;
}
Output:
Value of x: 20
Value via pointer: 20
Modifying Values via Pointers
#include <stdio.h>
void setToZero(int *p) {
*p = 0;
}
int main(void) {
int num = 5;
setToZero(&num);
printf("num after setToZero: %d\n", num);
return 0;
}
Output:
num after setToZero: 0
Checks for Understanding
- What happens if you dereference a
NULL
pointer? - How do you change the value that a pointer points to?
Show answers
- Undefined behavior (often a crash). Never do it.
- Use
*p = new_value;
wherep
points to valid storage.
Common Pitfalls
- Dereferencing an uninitialized or NULL pointer leads to undefined behavior (crash).
- Always ensure the pointer is valid before dereferencing.
Summary
The dereference operator *
is crucial for pointer manipulation and indirect access to variables in C. Practice using *
with pointers to understand its behavior.