4
Sep

C++ Tutorial – 09 – Arrays


Arrays are data structures used for storing
a collection of values that all have the same date type. To declare an array we begin as
we would a normal variable declaration, but also append a set of square brackets. The
brackets contain the number of elements in the array. The default values for these elements
are the same as for variables. For global arrays they become 0 and for local arrays
they are not initialized. To assign values to the elements we can reference
them one at a time, by placing the element’s index inside the square brackets, starting
with 0. We can also assign values at the same time as the array is declared by enclosing
them in curly brackets ({}). The specified array length can then be left out to let the
size be decided by the number of values assigned. Once the array elements are initialized we
access them simply by referencing the index of the element we want. Arrays can also be made multi-dimensional
by adding more sets of square brackets. As with single-dimensional arrays, they can either
be filled in one at a time or all at once during the declaration. Because arrays are made up of non-dynamic
memory their size must be determined before execution. Therefore, the size needs to be
a constant value. In order to create arrays with a variable length we need to use dynamic
memory, which is allocated with the new keyword and must be assigned to a pointer. Any array in C++ is actually a pointer to
the first element in the array. The referencing of array elements can just as well be made
with pointer arithmetics. By incrementing the pointer with one we move to the next element
in the array, because changes to a pointers address are implicitly multiplied by the size
of their data type. Keep in mind that just like with any other
pointer it’s possible to exceed the valid range of an array. It’s therefore important
to keep track of the array’s length. To determine the length of a statically allocated array
we can use the sizeof operator. But this cannot be used for dynamically allocated arrays.
The only way to know the size of this array is through the variable we used in its allocation.
When we’re done using a dynamic array we must remember to delete it, using the delete keyword
with an appended set of square brackets.

Tags: , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,

2 Comments

Leave a Reply

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