Labs ICT
โญ Pro Login

Pointers Introduction

Every variable you create in C lives somewhere in memory โ€” at some address. A pointer is just a variable that stores that address. Think of it like a signpost: instead of holding a value directly, it points to where the value lives.

The Address-of Operator (&)

The & operator gives you the memory address of a variable. It's like asking "where do you live?" instead of "what's your name?"


#include 
int main() {
  int x = 42;
  printf("Value: %d\n", x);
  printf("Address: %p\n", &x);
  return 0;
}
    
Try it Yourself โ†’

Declaring and Using Pointers

You declare a pointer with a type followed by *. To read the value at the address a pointer holds, use * โ€” that's dereferencing.


#include 
int main() {
  int x = 42;
  int *ptr = &x;
  printf("x = %d\n", x);
  printf("*ptr = %d\n", *ptr);
  *ptr = 99;
  printf("x after change = %d\n", x);
  return 0;
}
    
Try it Yourself โ†’

Why Pointers Exist

Pointers let you do things you simply can't do otherwise: modify variables in other functions, work with dynamic memory, build data structures like linked lists and trees, and handle arrays efficiently. Without pointers, C would lose most of its power.


#include 
void swap(int *a, int *b) {
  int temp = *a;
  *a = *b;
  *b = temp;
}
int main() {
  int x = 5, y = 10;
  swap(&x, &y);
  printf("x = %d, y = %d\n", x, y);
  return 0;
}
    
Try it Yourself โ†’

NULL Pointers

A pointer that doesn't point to anything should be set to NULL. Dereferencing a NULL pointer crashes your program โ€” always check before using.


#include 
int main() {
  int *ptr = NULL;
  if (ptr != NULL) {
    printf("%d\n", *ptr);
  } else {
    printf("Pointer is NULL\n");
  }
  return 0;
}
    
Try it Yourself โ†’

๐Ÿงช Quick Quiz

Which operator gets the memory address of a variable?