Pointers and Arrays

It’s Only Memory

Pointers and arrays are closely related to each other

  • Automatic conversion array ⟶ pointer

  • Array-type function parameters are in fact pointers to the first (0-th) array element

  • Index operator (a[i]) is pointer arithmetic

  • True strength of C

int a[] = { 42, 1, 23 };
char str[] = { 'h', 'a', 'l', 'l', 'o', '\0' };

int *pa1 = &a[0];
int *pa2 = a;

Conversion Array ⟶ Pointer

int a[3];
int *pa1 = &a[0];
int *pa2 = a;
../../../../../../_images/05-03-00-conv-pointer-array.svg

Pointer Arithmetic (1)

Pointer and array index

  • Pointer + Integer = Pointer

  • Equivalent to subscript (“index”) operator

  • Just like subscript there is no range check being made

  • ⟶ Errors happen

  • But: performance!

../../../../../../_images/05-03-00-pointer-plus-int.svg../../../../../../_images/05-03-00-pointer-plus-int-error.svg

Pointer Arithmetic (2)

Pointer increment

int *pa = a;
++pa;
../../../../../../_images/05-03-00-pointer-increment.svg

Pointer decrement

int *pa = &a[1];
--pa;
../../../../../../_images/05-03-00-pointer-decrement.svg

Pointer Arithmetic (3)

Pointers don’t necessarily point to something that is valid

pa = a + 4;  // or "pa += 4"
pa -= 2;
i = *pa; /* ok */
../../../../../../_images/05-03-00-pointer-out-of-range.svg
pa = a - 1;
pa += 2;
i = *pa; /* ok */
../../../../../../_images/05-03-00-pointer-out-of-range-negative.svg

Pointer Arithmetic: Difference

How many elements are there between two pointers?

p = &a[0];
q = &a[3];   // *one past* last valid element
num = q - p; /* 2 */
../../../../../../_images/05-03-00-pointer-diff.svg

Often (C++ STL) it is done like so:

  • Beginning of an array (“a set of elements”) is the pointer to the first element

  • End is pointer to one past the last valid element

Pointer Arithmetic: Array Algorithms

Iterating over all elements of the array

int sum(const int *begin, const int *end)
{
    int sum = 0;

    while (begin < end)
        sum += *begin++; /* precedence? what? */
    return sum;
}
../../../../../../_images/05-03-00-pointer-begin-end.svg

Beautiful, isn’t it?

Pointer Arithmetic: Jump Width? (1)

So far: pointer to int - how are arrays of other (even compound) types handled?

⟶ just the same!

  • Pointer + n: points n elements further

  • Type system is not stupid (only sometimes)

  • Pointer know which type is being pointed to

  • Be careful with void and void*: sizeof(void) is undefined!

Pointer Arithmetic: Jump Width? (2)

struct point
{
    int x, y;
};

struct point points[3], *begin, *end;

begin = points;
end = points + sizeof(points)/sizeof(struct point);

while (begin < end) {
    ...
    ++begin;
}

Pointer Arithmetic: Arbitrary Datatypes

  • sizeof: size (in bytes) of a type/variable

sizeof(int)
sizeof(struct point)
sizeof(i)
sizeof(pi)
sizeof(pp)
../../../../../../_images/05-03-00-pointer-plus-int-generalized.svg