APS105 L14 - Pointer Arithmetic

#APS105 Slides Lecture

Array Representation in Memory in C

Arrays are stored at a random, unused address by C.

Pasted image 20250224131632.png
How an int array is stored in memory. The addresses are adjacent, spaced by 4 cells.

Arrays cannot be treated as pass by values in functions

Since an array is essentially a pointer to where the array is stored, arrays cannot be treated as pass by values; instead, a copy of the address of the array is fed into the function.

Obtaining the index of an element in an array

Since arrays are contiguous (each element is stored in adjacent cells), if we know the address of the first element, we can also find the address of an ith element.

Key idea

C automatically computes sizeof() when dealing with pointer arithmetic, so adjacent elements in an array have address of startingAddress + i.

Getting the value of an array element by dereferencing a pointer is bad practice.

In the real world, you should almost always prefer to use array syntax (arr[i]) to get the value of an element, but on a test you might be forced to use pointer arithmetic to get it. Oh well.

Initializing a Pointer to a Safe Address

If you don't know the value of an int yet, you can:

NULL is a special address that is always invalid when dereferenced.

If you try to dereference a pointer that is set to NULL, you'll get a segmentation fault.