🎓 A1Learner
🔍
0 of 50 lessons completed

C Pointers

A pointer is a variable that holds an address. The last lesson found the address of a variable; this lesson stores that address and reads the value through it.

Hold an address

p holds the address of age. Reading the value through p prints 42, the value stored at that address.

#include <stdio.h>

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

Changing the value

The value changes through p, not through age. The print shows 99, so age itself has changed.

#include <stdio.h>

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

Two ways to read it

This program prints age and then prints the value through p. Both prints show the same value. Which one holds the value, and which one holds the address?

#include <stdio.h>

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

Example

#include <stdio.h>

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

Key points

  • A pointer is a variable.
  • A pointer holds the address of another variable.
  • int *p; declares a pointer to an int.
  • int *p = &age; makes p hold the address of age.
  • *p reads the value at the address in p.
  • Using *p to read the value is called dereferencing.
  • *p = 99; changes the value at the address in p.
  • Changing *p changes age itself, because p holds the address of age.
  • A pointer must hold a valid address before *p is used.

p holds the address of price. The first print reads the value through p, so it prints 30. The next line changes the value through p to 45. The last two prints both show 45, one from price and one through p.

Note

The * in a declaration and the * in *p look the same but do different jobs.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

When p holds the address of age, what does *p read?