Search Knowledge

© 2026 LIBREUNI PROJECT

C Programming Mastery / Memory Mastery

The Address Space: Pointer Fundamentals

What is a Pointer?

In C, a Pointer is a variable whose value is a memory address.

Think of RAM as a massive array of bytes. Each byte has a unique numerical index called its address. When you declare int x = 5;, the compiler allocates space in that array to hold the value 5. A pointer to x simply holds that numerical index.

Operators of Power: & and *

  1. The Address-of Operator (&): Returns the memory address of an object.
  2. The Indirection (Dereference) Operator (*): Accesses the value at the address held by a pointer.
int x = 42;
int *p = &x;  // 'p' holds the address of 'x'

printf("%d", *p); // Goes to the address in 'p' and reads the value (42)
*p = 100;         // Goes to the address in 'p' and overwrites it with 100

Pointers and Types

Why do we need different types of pointers (like int*, char*, double*) if every pointer just holds an address?

The type of a pointer tells the compiler:

  1. How many bytes to read/write when dereferencing.
  2. How to interpret those bytes (e.g., as a signed integer or a floating-point number).
  3. Instruction Scaling: How many bytes to jump when performing pointer arithmetic (e.g., p + 1 jumps by 4 bytes for an int* but only 1 byte for a char*).

The NULL Pointer

A NULL pointer is a pointer that points to “nothing” (usually address 0).

  • It is used to signify that a pointer is not yet initialized or that a search/allocation failed.
  • DANGER: Dereferencing a NULL pointer is Undefined Behavior and usually triggers a Segmentation Fault.
Interactive Lab

Dereferencing

int y = 10;
int *ptr = &y;
// How do we change the value of y to 20 using only ptr?
 = 20;

Why Use Pointers?

If pointers are so dangerous, why does C use them so heavily?

  1. Efficiency: Instead of copying a 10,000-byte structure into a function, we pass an 8-byte pointer (on 64-bit systems).
  2. Dynamic Memory: Pointers are the only way to access memory allocated at runtime (the Heap).
  3. Hardware Access: Pointers allow us to map specific memory addresses to hardware registers (common in embedded systems).
Runtime Environment

Interactive Lab

1#include <stdio.h>
2 
3int main() {
4 int a = 5, b = 10;
5 int *p1 = &a, *p2 = &b;
6
7 printf("Initially: a=%d, b=%d\n", a, b);
8
9 // Swapping via pointers
10 int temp = *p1;
11 *p1 = *p2;
12 *p2 = temp;
13
14 printf("After swap: a=%d, b=%d\n", a, b);
15 return 0;
16}
System Console

Waiting for signal...

Pointer Decay (Recap)

Remember that in C, the name of an array decodes to the address of its first element. Thus, int *p = arr; is shorthand for int *p = &arr[0];.