[RA] Ch9 Arryas

Reading Assignment: All of Programming Ch9 Arryas

Section 8.7 implies that pointer arithmetic is most useful when we have sequences of boxes that are guaranteed to be one after the other. Such sequences, called arrary are incredibly useful.

Motivating Example

Array is designed for repetitive work.

Array Declaration

A array is a sequnce of items of the same type. When an array is created, the programmer specifies its size. For example, if we wanted to declare an array of 4 ints called myArray, we would write:

int myArray[4];

As the array holds multiple values, we write the initialization data inside of curly braces, for example:

int myArray[4] = {42, 39, 16, 7};

If you write too many elements in curly braces(more than the number you assigned), it will give you a warning. If you wirte too few elements, it will fill the remaining ones in with 0.

If we provide an initializer, we can also omit the array size, and instead write empty square brackets–the compiler will count the elements of the initializer, and fill in the array size.

We’ll also note that you can use a similar syntax to initialize structs. For example, the following will initialize the first field of p to 3 and the sencond field to 4:

point p = {3, 4}

However, for structs, such initialization is brittle. You may want to designate which element you are initializing with:

point p = {.x = 3, .y = 4};

You can also initialize an array of structs in thisway:

point myPoints[] = {{.x = 3, .y = 4}};

Accessing an Array

We will note that accessing an array out of bounds is an error that the compiler cannot detect. If you write such code, your program will access some box, but you do not know what box it actually is. In fact, pointer arithmetic and array indexing are exactly the same under the hood, the compiler turns myArray[i] into *(myArray + i).

Passing Arrays as Parameters

When we pass a pointer that actually points at an array, we can index it like an array, and perform pointer arithmetic on it. Such pointer arithmetic will be well defined, as long as the resulting pointer remains within the bounds of the array, as we are guaranteed that the array elements are sequential in memory.

Writing Code with Arrays

Index of Largest Element

Video 9.5.1

Closest Point

Video 9.4 Tranlslating our cloest point algorithm to code.

Dangling Pointers

Whenever you have a pointer to something whose memory has been deallocated, it is called a dangling pointer. Dereferencing a dangling pointer results in undefined behavior (and thus represents a serious problem with your code) because you have no idea what values are at the end of the arrow.

Sizeof Arrays: size_t

size_t is designed for “unsigned integers that describe the size of things”.

While we are discussing the sizes of data, it is a good time to introduce the sizeof operator, which evaluates the number of bytes which the type requires.