Pointers (Lesson)

Pointers: Mastering Memory

A pointer is a variable that stores the memory address of another variable. They are the most powerful and unique feature of C.

15.1 Basics of Pointers

The Address-of Operator (&)

Used to get the memory address of a variable.

int num = 10;
printf("Address of num: %p", &num);

The De-referencing Operator (*)

Used to get the value stored at a specific memory address.

int num = 10;
int *ptr = # // ptr stores address of num
printf("Value via ptr: %d", *ptr); // Prints 10

15.2 Pointer Declaration and Initialization

Always initialize pointers to NULL if you don't assign them an address immediately.

int *ptr = NULL; 

15.3 Pointer Arithmetic

You can perform arithmetic on pointers (+, -, ++, --). Every increment/decrement shifts the address by sizeof(type).

int arr[3] = {10, 20, 30};
int *ptr = arr; // points to 10
ptr++; // now points to 20 (address + 4 bytes)

15.4 Pointers and Arrays

The name of an array is actually a pointer to its first element. arr[i] is equivalent to *(arr + i).

int arr[] = {10, 20, 30};
printf("%d", *(arr + 1)); // Prints 20

15.5 NULL and void Pointers

  • NULL Pointer: A pointer that points to nothing. Used for error checking.
  • Void Pointer (void *): A generic pointer that can point to any data type. It cannot be de-referenced without typecasting.

Example: Swapping Two Numbers using Pointers

#include <stdio.h>

void swap(int *n1, int *n2) {
    int temp;
    temp = *n1;
    *n1 = *n2;
    *n2 = temp;
}

int main() {
    int a = 5, b = 10;
    printf("Before: a=%d, b=%d\n", a, b);
    
    // Pass by Reference
    swap(&a, &b);
    
    printf("After: a=%d, b=%d\n", a, b);
    return 0;
}

Refer to the Lecture Slides for a visualization of Multi-level Pointers (Pointer to Pointer).

PREVIOUS
Arrays
NEXT
Strings