C ยท Chapter 23 of 45

C Pointers

A pointer is a variable that stores the memory address of another variable, rather than a value directly. Pointers are declared using the * symbol, and are one of C's most distinctive and powerful features.

To get the value stored at the address a pointer holds, you 'dereference' it, also using the * symbol. Pointers enable efficient memory use, dynamic data structures, and passing data by reference.

Syntax
type *pointerName = &variable;

Declaring and using pointers

A pointer declaration looks like `int *p;`, meaning p can hold the address of an int. Assign it an address with `p = &age;`, then access the value it points to with `*p`.

Why pointers matter

Pointers let functions modify variables outside their own scope, enable dynamic memory allocation, and make working with arrays and strings efficient.

Example 1 (c)
#include <stdio.h>

int main() {
  int age = 25;
  int *p = &age;
  printf("%d\n", *p);
  return 0;
}
Output
25

p stores the address of age, and *p dereferences it to get the value 25.

Example 2 (c)
#include <stdio.h>

int main() {
  int age = 25;
  int *p = &age;
  *p = 30;
  printf("%d\n", age);
  return 0;
}
Output
30

Writing through the dereferenced pointer *p changes the original variable age.

Key points

  • A pointer stores the memory address of another variable.
  • The * symbol both declares a pointer and dereferences it.
  • Dereferencing lets you read or modify the pointed-to value.
  • An uninitialized pointer is dangerous and should be set to NULL if unused.
๐Ÿ’ก Note: Always initialize pointers before use; dereferencing an invalid or NULL pointer causes a crash.

๐Ÿ“ Quick Quiz

1. What does a pointer variable store?

2. What does *p do when p is a pointer?

3. What is a safe value to assign an unused pointer?