Algorithms

Pointers in programming: the address on paper, not the house

Cover of the article Pointers in programming: the address on paper, not the house
Focused reading

Understand the context.
Put it into practice.

Leia este artigo em português

In this article
  1. What is a memory address?
  2. How do you create and use a pointer?
  3. What is a pointer for? The swap inside a function
  4. Now you ask: does the array have anything to do with pointers?
  5. What is NULL?
  6. What about Go, which also has pointers?
  7. And in Python and PHP, are there pointers?
  8. How does the same concept show up in each language?
  9. Now you ask: what do pointers have to do with performance?
  10. What are the most common mistakes with pointers?
  11. Now it’s your turn!

A pointer is a variable that stores a memory address, instead of storing an ordinary value, like a number or a letter. With the address in hand, the program can get to the data that lives there, to read it or to change it.

In the article on functions, you saw that a function receives data and returns a result. In the article on tuples, you swapped two values in Python with a single line. Now try to do that same swap in C, inside a function. It doesn’t work! And the reason is today’s topic. Pointers have a reputation for being hard, but the idea fits in one sentence: a pointer is an address written down. And it doesn’t belong to a single language: C and Go have pointers with that name, and Python and PHP use the same principle of getting to a piece of data without making another copy of it. This article starts with C, where the address shows up with no disguise, goes through the other three languages and ends with what pointers have to do with performance.

Think of a friend’s address written down on a piece of paper. The paper isn’t the house: it’s just the way to get there. With the paper in hand, you can go there and drop off a package. And you can make several copies of the paper without building any house. The pointer is the paper, and the variable is the house.

Three-panel comic: a person with the address 1000 written on a piece of paper goes to the house numbered 1000 to drop off a package, and two people with copies of the paper point to the same house
The pointer is the paper with the address, and the variable is the house.

What is a memory address?

Your computer’s memory is a long row of bytes, and each byte has a number: its address. Every variable takes up some of these bytes, and its address is the address of the first byte it takes up. That’s how the Memory and Pointers lecture of Binghamton University’s CS 220 course presents the subject.

In C, the & operator returns the address of a variable:

#include <stdio.h>

int main(void)
{
    int age = 30;

    printf("value: %d\n", age);
    printf("address: %p\n", (void *) &age);
    return 0;
}

Output (the address changes on every run):

value: 30
address: 0x7ffeff394f54

The number that starts with 0x is in hexadecimal, base 16. You don’t need to memorize or interpret this number: what matters is that it exists and identifies where the variable lives.

How do you create and use a pointer?

There are two new symbols, and both of them appear in this program:

#include <stdio.h>

int main(void)
{
    int age = 30;
    int *pointer = &age; // stores the address of age

    printf("%d\n", *pointer); // reads the value at the address

    *pointer = 31; // changes the value at the address
    printf("%d\n", age);
    return 0;
}

Output:

30
31
SymbolWhere it appearsWhat it means
&&ageThe address of the variable age
* in the declarationint *pointerThis variable is a pointer to an integer
* in use*pointerThe value at the stored address
The two operators used with pointers in C.
Diagram of a pointer that stores the address 1000 and points to the variable age, whose value is 30
The pointer stores the address, and the address leads to the value.

When the pointer stores the address of age, we say it points to age. Look at the last part of the program: the line *pointer = 31 doesn’t mention the variable age, but that’s the one that changed. Got it? Whoever has the address can change the value.

IMPORTANT: the asterisk has two roles. In the declaration, it says that the variable is a pointer. In use, it tells the program to fetch the value at the address. And neither of them is multiplication.

What is a pointer for? The swap inside a function

Here’s the problem from the beginning of the article. The two functions below try to swap two values. Only one of them can do it:

#include <stdio.h>

void swap_wrong(int a, int b)
{
    int temp = a;
    a = b;
    b = temp;
}

void swap(int *a, int *b)
{
    int temp = *a;
    *a = *b;
    *b = temp;
}

int main(void)
{
    int x = 5;
    int y = 3;

    swap_wrong(x, y);
    printf("%d %d\n", x, y);

    swap(&x, &y);
    printf("%d %d\n", x, y);
    return 0;
}

Output:

5 3
3 5
Diagram comparing the function that receives copies of x and y, and doesn’t swap them, with the function that receives their addresses, and does
On the left, the function swaps the copies. On the right, it reaches the variables through their addresses.

The first function receives copies of the values. It swaps the copies, finishes, and the original variables stay as they were. The second one receives the addresses and, with them, reaches the real variables. That’s why the call changes: swap(&x, &y), with the & in front of each one. Harvard’s CS50 course uses this same pair of functions, the one that fails and the one that works, to show why pointers exist.

Now you ask: does the array have anything to do with pointers?

Everything! The values of an array sit next to each other in memory. And the name of the array works as the address of the first value:

#include <stdio.h>

int main(void)
{
    int grades[3] = {7, 8, 9};
    int *pointer = grades; // the same as &grades[0]

    printf("%d\n", *pointer);
    printf("%d\n", *(pointer + 1));
    printf("%d\n", pointer[2]);
    return 0;
}

Output:

7
8
9

The three lines read the array in different ways. The middle one adds 1 to the pointer, and the compiler understands that it should move forward one integer, not one byte. In C, v[i] and *(v + i) are two ways of writing the same thing.

What is NULL?

It’s the value of a pointer that doesn’t point anywhere. It works as a warning: “there’s no valid address here yet”. Before using a pointer that may be empty, the program checks:

#include <stdio.h>

int main(void)
{
    int *pointer = NULL; // doesn't point to anything yet

    if (pointer == NULL) {
        printf("empty pointer\n");
    }

    int age = 30;
    pointer = &age;

    if (pointer != NULL) {
        printf("%d\n", *pointer);
    }
    return 0;
}

Output:

empty pointer
30

You’ll see this check all the time in data structures: it’s with NULL that a linked list marks its end.

What about Go, which also has pointers?

Go has pointers with the same two symbols as C: & returns the address, and * gets to the value. The program below brings together three examples from this article: reading and changing through the address, swapping two values inside a function, and checking the empty pointer.

package main

import "fmt"

func swap(a *int, b *int) {
	temp := *a
	*a = *b
	*b = temp
}

func main() {
	age := 30
	pointer := &age // stores the address of age

	fmt.Println(*pointer) // reads the value at the address
	*pointer = 31         // changes the value at the address
	fmt.Println(age)

	x, y := 5, 3
	swap(&x, &y)
	fmt.Println(x, y)

	var empty *int // doesn't point to anything yet
	fmt.Println(empty == nil)
}

Output:

30
31
3 5
true

The swap works for the same reason: the function receives the addresses. And a pointer that hasn’t received an address yet is nil, which plays the role of NULL.

IMPORTANT: Go took two traps out of the way. The first one is math with addresses. I tried to write pointer + 1, as in the C array example, and the program didn’t even compile. The Go documentation explains that this choice was made for safety. The second one is the empty pointer: when I tried to read the value of a pointer that was nil, the program stopped right away, with a clear message:

invalid operation: pointer + 1 (mismatched types *int and untyped int)
panic: runtime error: invalid memory address or nil pointer dereference

The first line comes from the compiler. The second one appeared during execution.

And in Python and PHP, are there pointers?

Not with that name, and not with an asterisk. But the idea of “two paths to the same data” exists, and it explains a behavior that catches a lot of people by surprise. Look at it in Python:

a = [1, 2, 3]
b = a  # b isn't a copy: it's another name for the same list
b.append(4)
print(a)

Output:

[1, 2, 3, 4]

The program touched b, and it was a that changed! The two variables are names for the same list. In PHP, the & in front of a parameter makes the function change the original variable:

<?php

function double_it(int &$number): void
{
    $number = $number * 2;
}

$value = 21;
double_it($value);
echo $value, "\n";

Output:

42

The PHP manual makes a point of warning that the language’s references aren’t pointers like the ones in C: they don’t store memory addresses and don’t allow math with addresses. For the programmer, though, the effect is similar. Focus on the concept, not the language!

How does the same concept show up in each language?

The name changes, the symbols change, and the idea stays the same: storing the path to a piece of data, instead of storing another copy of it. Here are the four languages of this article side by side:

LanguageHow the idea shows upWhat the examples showed
CPointer, with & and *, and with address math*(pointer + 1) read the second value of the array
GoPointer, with & and *, without address mathpointer + 1 didn’t even compile
PythonTwo names bound to the same objectb.append(4) changed the list a
PHPReference, with & in the parameterThe double_it function changed the caller’s variable
One concept, four ways of writing it.

In Python, the rule is in the documentation: assignment doesn’t copy the object, it only binds a name to it. That’s why b = a didn’t create a second list.

Now you ask: what do pointers have to do with performance?

Everything! You saw in the swap function that a function receives copies of the data. With an integer, the copy costs almost nothing. With a large piece of data, the computer has to copy it byte by byte on every call. Passing the address avoids that work: all that travels to the function is the address.

The program below measures the difference. It creates a package with 250 thousand integers and calls two functions, ten thousand times each: the first one receives a copy of the package, and the second one receives its address. The package is a struct, the subject of the next article. For now, all you need to know is that it groups several pieces of data into a single variable.

#include <stdio.h>
#include <time.h>

struct Photo
{
    int points[250000]; // a package with 250 thousand integers
};

int read_with_copy(struct Photo photo) // receives a copy of the whole package
{
    return photo.points[0] + photo.points[249999];
}

int read_with_address(struct Photo *photo) // receives only the address of the package
{
    return (*photo).points[0] + (*photo).points[249999];
}

int main(void)
{
    struct Photo photo = {0}; // starts with zero in every position
    photo.points[0] = 1;
    photo.points[249999] = 2;

    printf("package size: %zu bytes\n", sizeof(photo));
    printf("address size: %zu bytes\n", sizeof(&photo));

    int sum = 0;
    clock_t start = clock();
    for (int i = 0; i < 10000; i++) {
        sum = sum + read_with_copy(photo);
    }
    double with_copy = (double) (clock() - start) * 1000 / CLOCKS_PER_SEC;

    start = clock();
    for (int i = 0; i < 10000; i++) {
        sum = sum + read_with_address(&photo);
    }
    double with_address = (double) (clock() - start) * 1000 / CLOCKS_PER_SEC;

    printf("sum of the reads: %d\n", sum);
    printf("ten thousand calls with a copy: %.0f ms\n", with_copy);
    printf("ten thousand calls with the address: %.0f ms\n", with_address);
    return 0;
}

Output (the times change on every run and from one computer to another):

package size: 1000000 bytes
address size: 8 bytes
sum of the reads: 60000
ten thousand calls with a copy: 385 ms
ten thousand calls with the address: 0 ms

The package takes up 1,000,000 bytes, and its address, 8 bytes. With the copy, each call carried the million bytes, and the ten thousand calls took 385 milliseconds. With the address, they took less than 1 millisecond. The test was compiled with GCC without optimization options.

In Go, the rule is the same. The language’s documentation says that everything is passed by value, that passing a pointer copies the pointer, not the data it points to, and that, when the data is large, using a pointer can be cheaper.

That’s why the concept comes back in so many subjects:

  • In functions: the address lets a function change the caller’s data.
  • In data structures: in C, pointers are what link one element to the next. That’s how you build the linked list, which comes later in this journey.
  • In optimization: the address avoids copies that cost time and memory.

IMPORTANT: avoiding the copy has a price. Whoever receives the address can change the original data, on purpose or by mistake. That’s what happened to the list a in the Python example.

What are the most common mistakes with pointers?

  • Using a pointer that hasn’t received an address. A pointer that was just created holds an arbitrary address. A good practice is to start with NULL and check before using it.
  • Forgetting the & in the call. Writing swap(x, y) passes the values, not the addresses. GCC compiles it, but warns: passing argument 1 of 'swap' makes pointer from integer without a cast. A compiler warning deserves to be read!
  • Mixing up the two asterisks. int *p declares. *p = 10 uses.
  • Forgetting that the function receives copies. If the function needs to change a variable of the caller, it needs to receive the address.

Now it’s your turn!

First on paper. Draw the memory boxes and follow this snippet, line by line: int x = 10;, then int *p = &x;, then *p = *p + 5; and, finally, int y = *p;. What are the values of x and y at the end? Write it down and only then check it on the computer.

Then write a function double_it that receives the address of an integer and doubles the value stored there. Call the function in main and show the result. Try it on your own, without asking anyone for the ready-made answer, not even AI!

In the next article of this foundations series: struct, malloc and free. With them, plus pointers, you build a linked list. See you there!

Stay confident!!!

Sources:

  • Binghamton University, CS 220 (Spring 2019). Memory and Pointers, with the address of each byte of memory, the address of a variable as the location of its first byte, the & operator as “address of” and the * operator as “value at” (PDF, lecture slides).
  • Harvard University, CS50. Lecture 4, with the & and * operators, the pointer as a variable that stores an address, and the swap function that fails with copies and works with pointers.
  • Stanford University, CS Education Library (Nick Parlante). Pointer Basics, with the pointer and its pointee, and the dereference that only works when the pointer has a pointee.
  • Stanford University, CS Education Library (Nick Parlante). Pointers and Memory, with the & operator, value parameters as local copies, and the Swap() function as the standard example of reference parameters (PDF).
  • Dartmouth College, CS 50: Software Design and Implementation. Lecture notes on C pointers, with memory as a sequence of bytes, each with its own numeric address, parameters passed by value, and pointers that move in multiples of the size of the base type.
  • Cornell University, CS 3410. Pointers, with the dereference operator, the star that is part of the type name in a declaration and the dereference operator in use, and NULL as a pointer that doesn’t point to anything.
  • Go, official documentation. The Go Programming Language Specification, with the pointer type and the nil value of a pointer that hasn’t been initialized.
  • Go, official documentation. Frequently Asked Questions, with the answers on why Go has no pointer arithmetic, on parameters passed by value and on using a pointer with large data.
  • Python, official documentation. copy: Shallow and deep copy operations, with the explanation that assignment statements don’t copy objects, they create bindings between a target and an object.
  • PHP, official manual. What References Are, with the warning that references aren’t like C pointers: they aren’t memory addresses and don’t allow pointer arithmetic.
  • PHP, official manual. What References Are Not, with the reminder that references aren’t pointers.
  • The examples were run on Python 3.13, PHP 8.3, GCC 13 and Go 1.24.

Share this article

About the author

Walmir Silva

Hi! I'm Walmir, a software engineer with an MBA in Software Engineering, the mind behind GrowthCode and the author of the book "Além do Código" (in Portuguese).

If you think programming is just about writing code, get ready to broaden your horizons. Here, we go beyond the code and explore the fascinating intersections between technology, business, the arts and philosophy.

Are you looking for career growth? Do you want to stand out in a competitive market? Are you after a life richer in knowledge and fulfillment? Then you've come to the right place. At GrowthCode, we offer deep insights, proven strategies and a touch of philosophical wisdom to fuel your personal and professional growth.

See all articles →

Continue the conversation

Share your perspective

Your email address will not be published. Required fields are marked *

We keep the IP address and browser of commenters for 6 months, to block spam and because Brazil’s Marco Civil da Internet requires access records to be kept for that period. See how we handle your data (in Portuguese).

Find your next answer

What do you want to learn?

Cookie preferences

Optional cookies start off. You can change your choice at any time on this screen.

NecessaryAlways on

They store your cookie choice and its record code, and keep the site working. They are not used for advertising.

They count visits and show how the site is used: Google Analytics and Microsoft Clarity, loaded by Google Tag Manager.

They show Google AdSense ads without personalization. The cookies in this category limit how often ads repeat and measure their results.

Uses your browsing to choose ads and build ad audiences: Google ads chosen by your interests and Google signals in Analytics. When off, ads are shown without personalization. Requires Advertising.

You can also block cookies in your browser settings. Details in the Privacy policy (in Portuguese).