Introduction to C Pointers
An introduction to C Pointers
Pointers are one of the most confusing/challenging parts of C, in my opinion. Especially if you are new to programming, but also if you come from a higher level programming language like Python or JavaScript.
In this post I want to introduce them in the simplest yet not-dumbed-down way possible.
A pointer is the address of a block of memory that contains a variable.
When you declare an integer number like this:
int age = 37;
We can use the &
operator to get the value of the address in memory of a variable:
printf("%p", &age); /* 0x7ffeef7dcb9c */
I used the %p
format specified in printf()
to print the address value.
We can assign the address to a variable:
int *address = &age;
Using int *address
in the declaration, we are not declaring an integer variable, but rather a pointer to an integer.
We can use the pointer operator *
to get the value of the variable an address is pointing to:
int age = 37;
int *address = &age;
printf("%u", *address); /* 37 */
This time we are using the pointer operator again, but since it’s not a declaration this time it means “the value of the variable this pointer points to”.
In this example we declare an age
variable, and we use a pointer to initialize the value:
int age;
int *address = &age;
*address = 37;
printf("%u", *address);
When working with C, you’ll find that a lot of things are built on top of this simple concept, so make sure you familiarize with it a bit, by running the above examples on your own.
Pointers are a great opportunity because they force us to think about memory addresses and how data is organized.
Arrays are one example. When you declare an array:
int prices[3] = { 5, 4, 3 };
The prices
variable is actually a pointer to the first item of the array. You can get the value of the first item using this printf()
function in this case:
printf("%u", *prices); /* 5 */
The cool thing is that we can get the second item by adding 1 to the prices
pointer:
printf("%u", *(prices + 1)); /* 4 */
And so on for all the other values.
We can also do many nice string manipulation operations, since strings are arrays under the hood.
We also have many more applications, including passing the reference of an object or a function around, to avoid consuming more resources to copy it.
→ I wrote 17 books to help you become a better developer, download them all at $0 cost by joining my newsletter
→ JOIN MY CODING BOOTCAMP, an amazing cohort course that will be a huge step up in your coding career - covering React, Next.js - next edition February 2025