Technical Articles
F5 SMEs share good practice.
cancel
Showing results for 
Search instead for 
Did you mean: 
Custom Alert Banner

Quick Intro

Pointers have always been the most confusing aspect of C for new learners.

As a former lecturer, I find simple hands-on examples are the best to get one started.

In this article, I will explain the following:

  • What a pointer is
  • How a pointer is declared in C
  • How to assign a memory address to a pointer
  • How to change values using pointers
  • How to move pointer to a different memory address

What is a pointer?

It's literally a variable that stores and point to the memory address of another variable.

Don't worry, it should be clear once we go through some examples.

How a pointer is declared in C

0151T000003leqzQAA.png

How to assign a memory address to a pointer

Now, imagine there's a variable x like this:

0151T000003lerEQAQ.png

The &x just means we're assigning to p the memory address of x:

0151T000003lerJQAQ.png

In order to retrieve the value 5 from p, we also need to use *p because p (without *) retrieves the memory address of x and *p goes after the value stored in the memory's address.

Here's the proof:

0151T000003lerOQAQ.png

Notice that C understands that adding & in front of variable retrieves its memory address.

How to retrieve pointer's value

Retrieving pointer's is also known as dereferencing pointer.

If we change *p we also change x.

We can also assign the value that *p points to a different variable too (effectively changing the value of x😞

0151T000003lerKQAQ.png

How to change values using pointers

When we point a pointer to an array, it will point to the memory address of array's first item at index 0:

0151T000003lerTQAQ.png

The pointer behaves in the same way as if were making the changes to the array:

0151T000003lerYQAQ.png

How to move pointer to a different memory address

In this example, I pointed p to A's memory address and then pointed p to n's memory address and that's fine:

0151T000003lersQAA.png

Let's uncomment last line so we can see that we can't do the same with arrays, i.e. re-assigning values:

0151T000003lerxQAA.png

Hope that clarifies a bit of the mystery behind pointers.

Comments
JRahm
Community Manager
Community Manager

Nice work, Rodrigo! It's been since 1996 since I've dealt directly with C on a consistent basis, so it was nice to revisit an old friend. It also led me to investigate why python (my personal fave) doesn't really have pointers, and this article on Real Python does a great job showing the differences between C and python architecture, why pointers aren't really necessary in python, and of course ways to simulate or engage with pointers if you really must.

Yeah, C is the old school thing that never gets outdated. I liked the last bit about emulating pointers in Python. Thanks for sharing that, Jason!

Version history
Last update:
‎20-Feb-2020 03:25
Updated by:
Contributors