Lesson 16 of 31

Pointers

Pointers

A pointer is a variable that holds the memory address of another variable. Pointers are fundamental to C -- they enable dynamic data structures, efficient parameter passing, and direct memory manipulation.

Address-of and Dereference

  • &x -- the address-of operator gives you the address of variable x
  • *p -- the dereference operator reads or writes the value at the address stored in p
int x = 42;
int *p = &x;       // p holds the address of x
printf("%d\n", *p); // 42 -- dereference p to read x's value
*p = 99;            // write 99 to the address p points to
printf("%d\n", x);  // 99 -- x was modified through p

Tractor beams: a pointer locks onto the exact memory address, just like a tractor beam locks onto a ship's coordinates.

Pointer Types

A pointer's type determines what type it points to:

int *ip;     // pointer to int
char *cp;    // pointer to char
long *lp;    // pointer to long

Pointer Arithmetic

Adding 1 to a pointer advances it by sizeof(*p) bytes:

int arr[3] = {10, 20, 30};
int *p = arr;       // points to arr[0]
printf("%d\n", *p);     // 10
printf("%d\n", *(p+1)); // 20
printf("%d\n", *(p+2)); // 30

NULL Pointer

A pointer that doesn't point to anything should be set to NULL:

int *p = NULL;  // or: int *p = 0;

Your Task

Write a function void swap(int *a, int *b) that swaps the values of two integers using pointers. Use it to swap x=10 and y=20, then print both values.

TCC compiler loading...
Loading...
Click "Run" to execute your code.