algoritmauzmanı
TREN
1Introduction
Lesson 1.2

Memory, addresses and pointers

Linked lists, trees and graphs connect their nodes with addresses. To understand these structures you first need to know how memory is numbered and how a variable that holds an address, a , works. This lesson explains it in C and then shows the equivalent in Java and Python.

What you will learn
  • That memory is made of numbered bytes, and what the address of a variable means
  • Taking an address with & in C, reaching the value at an address with *, and the value
  • Why a pointer to a pointer (struct Node**) is needed, and how Java and Python references differ
8 min

1Memory: numbered bytes

You can think of a computer's main memory as a very long row of boxes. Each box is one byte, and every byte has a number. That number is called an . Addresses are usually written in base 16: 0x1000, 0x1004 and so on.

A variable takes up one or more bytes. On most systems an int is 4 bytes; the address of such a variable is the number of the first byte it occupies. For a program to reach a value means knowing that value's address.

2A variable's address and pointers

In C the & operator gives the address of a variable. To store an address you use a : a variable that holds not the value itself but where the value sits in memory. The type int* means a pointer that holds the address of an int.

int x = 42;int* p = &x;          // p holds the address of xprintf("%d\n", *p);   // 42: the value where p points*p = 50;              // x is now 50

The same * sign does two jobs. In a declaration (int* p) it says the type is a pointer. In an expression (*p) it goes to the address the pointer holds and reads or writes the value there. The second use is called dereferencing the pointer.

70x1000150x1004420x100830x100c00x10100x1008p0x2000
Each box is an int (4 bytes). The 42 at address 0x1008 is the value of x. The value of p is that address; the arrow shows where p points. p also lives in memory and has its own address (0x2000).

Adding 1 to a pointer moves the address on not by one byte but by the size of the type it points to. If p is an int*, p + 1 points four bytes further on, at the next int. Indexing into an array relies on this calculation.

3NULL: a pointer that points nowhere

When a pointer has nowhere to point yet, it is given . In a linked list the field of the last node and the of an empty list are NULL. Dereferencing a NULL pointer is undefined behaviour; on most systems the program crashes. So you check before dereferencing:

int* q = NULL;if (q != NULL) {    printf("%d\n", *q);   // only if q points somewhere}

4Allocating and freeing memory

The nodes of a linked list are created one by one while the program runs. In C you use for this: it allocates the requested number of bytes and returns the address of that block. If no memory is left it returns NULL. When you are done, the block is given back with ; if it is not, you get a .

int* d = malloc(sizeof(int));   // allocate 4 bytesif (d != NULL) {    *d = 7;    free(d);    // give the block back    d = NULL;   // do not keep the old address}

After free, d still holds the old address. A pointer that keeps using that address is a ; setting the pointer to NULL makes the mistake visible.

5Pointers to pointers

In C, functions receive copies of their arguments. If you pass a pointer to a function, the function can change the value the pointer points to, but it cannot change the caller's pointer; only the copy changes. Every linked list operation that changes the runs into this problem.

void setHeadWrong(struct Node* head, struct Node* node) {    head = node;    // only the copy changes} void setHead(struct Node** head, struct Node* node) {    *head = node;   // the caller's head changes} // call it as: setHead(&head, node);

The fix is to pass the address of the pointer itself. struct Node** is a : it holds the address of the head variable. Writing *head inside the function reaches the caller's head variable itself.

42x0x10080x1008p0x20000x2000pp0x3000
pp holds the address of p, and p holds the address of x. *pp is p itself, and **pp is 42.

You will see this pattern often in the linked list lessons; it is first used in Inserting at the head.

6References in Java and Python

In Java and Python you do not write pointers; objects are held through . A reference points to an object much like a pointer, but there are no & and * operators and no address arithmetic. Assigning a reference to another variable does not copy the object; it creates a second reference to the same object:

Node a = new Node(5);Node b = a;     // b and a refer to the same objectb.data = 9;     // a.data is now 9 too
a = Node(5)b = a       # b and a refer to the same objectb.data = 9  # a.data is now 9 too

The counterpart of NULL is null in Java and None in Python. Trying to reach a field through a null reference throws a NullPointerException in Java; doing the same on None raises an AttributeError in Python. Memory is not freed by hand either: cleans up objects that no reference can reach.

Both languages pass a copy of the reference to a function. The function can change the object's fields, but it cannot make the caller's variable refer to a different object. That is why, in Java and Python, operations that change the head node return the new head.

7Try it

After int x = 5; int* p = &x; *p = 8; what is x?

Show the answer

The answer is B. p holds the address of x. *p = 8 writes 8 to that address, which changes x itself. The value of p, the address, does not change.

In C, why does a function that changes the head of a list take struct Node** head instead of struct Node* head?

Show the answer

The answer is B. C passes arguments by copying them. Changing a copy of head does not affect the caller. When &head is passed, the function writes to the real variable through *head. In Java and Python the same job is done by returning the new head.

Lessons you mark show up in the curriculum. This is kept on this device only.