Search

6.1 — Arrays (Part I)

In lesson 4.7 -- Structs, you learned that you can use a struct to aggregate many different data types into one identifier. This is great for the case where we want to model a single object that has many different properties. However, this is not so great for the case where we want to track many related instances of something.

Fortunately, structs are not the only aggregate data type in C++. An array is an aggregate data type that lets us access many variables of the same type through a single identifier.

Consider the case where you want to record the test scores for 30 students in a class. Without arrays, you would have to allocate 30 almost-identical variables!

Arrays give us a much easier way to do this. The following array definition is essentially equivalent:

In an variable declaration, we use square brackets ([]) to tell the compiler both that this is an array variable (instead of a normal variable), as well as how many variables to allocate (called the array length).

In the above example, we declare a fixed array named testScores, with a length of 30. A fixed array (also called a fixed length array or fixed size array) is an array where the length is known at compile time. When testScores is instantiated, the compiler will allocate 30 integers.

Array elements and subscripting

Each of the variables in an array is called an element. Elements do not have their own unique names. Instead, to access individual elements of an array, we use the array name, along with the subscript operator ([]), and a parameter called a subscript (or index) that tells the compiler which element we want. This process is called subscripting or indexing the array.

In the example above, the first element in our array is testScores[0]. The second is testScores[1]. The tenth is testScores[9]. The last element in our testScores array is testScore[29]. This is great because we no longer need to keep track of a bunch of different (but related) names -- we can just vary the subscript to access different elements.

Important: Unlike everyday life, where we typically count starting from 1, in C++, arrays always count starting from 0!

For an array of length N, the array elements are numbered 0 through N-1! This is called the array’s range.

An example array program

Here’s a sample program that puts together the definition and indexing of an array:

This prints:

The lowest prime number is: 2
The sum of the first 5 primes is: 28

Array data types

Arrays can be made from any data type. Consider the following example, where we declare an array of doubles:

This program produces the result:

The average is 3.1

Arrays can also be made from structs. Consider the following example:

To access a struct member of an array element, first pick which array element you want, and then use the member selection operator to select the struct member you want:

Arrays can even be made from arrays, a topic that we’ll cover in a future lesson.

Array subscripts

In C++, array subscripts must always be an integral type (char, short, int, long, long long, etc… -- and strangely enough, bool). These subscripts can be either a constant or non-constant value.

Here are some examples:

Fixed array declarations

When declaring a fixed array, the size of the array (between the square brackets) must be a compile-time constant. This is because the size of a fixed array must be known at compile time. Here are some different ways to declare fixed arrays:

Note that in the last two cases, an error would result because size is not a compile-time constant.

A note on dynamic arrays

Because fixed arrays have memory allocated at compile time, that introduces two limitations:

  • Fixed arrays cannot have a length based on either user input or some other value calculated at runtime.
  • Fixed arrays have a fixed length that can not be changed.

In many cases, these limitations are problematic. Fortunately, C++ supports a second kind of array known as a dynamic array. The length of a dynamic array can be set at runtime, and their length can be changed. However, dynamic arrays are a little more complicated to instantiate, so we’ll cover them later in the chapter.

Summary

Fixed arrays provide an easy way to allocate and use multiple variables of the same type so long as the size of the array is known at compile time.

We’ll look at more topics around fixed arrays in the next lesson.

6.2 -- Arrays (Part II)
Index
7.x -- Chapter 7 summary and quiz

65 comments to 6.1 — Arrays (Part I)

  • Hi Alex,
    we know that the name of an array is a pointer to the first element of the array.

    if we compile this program the output will be something like this ~~~> 0x22fe30

    But why this is not true for chars :

    this program's output will be this ~~~> Hello

  • Nitin Singh

    The output of first example of array's program needs some attention!

  • I think dynamic array size (run time constant) allocation is dependent on compiler. It doesn't necessarily have to be a compile time constant.
    The following code works on Linux, GCC compiler. I tried compiling it with -std=c++11 and without this flag. It works both times.

    [link]https://stackoverflow.com/questions/737240/c-c-array-size-at-run-time-w-o-dynamic-allocation-is-allowed[/link] Apparently this has been updated in c++99 standard and also in C++ 14

    I don't know if this is a bad practice or frowned upon.

    • Alex

      A few things:
      * There is no C++99 standard. There IS a C99 standard that introduced new features into the C language (including variable length arrays). Features adopted into C99 are not automatically included in C++.
      * Although variable length arrays were in the C++14 draft standard for a while, it appears they were removed before the final draft. Consequently, they are not officially supported in C++.
      * Some compilers still support them for backwards compatibility reasons. However, because they are not an official part of the C++ language, best practice would be to not use them. Use std::vector instead, as it probably does what you want anyway.

  • What do you mean by OS-level functionality

    • Alex

      Operating systems such as Windows often include functionality to do user-interface or basic graphics.

      Personally, I'd avoid these, as they're not cross-platform compatible.

  • Hey Alex, first of all thank you so much for the tutorials. My question is how to work with graphics in C++...? Whenever I run my programs, the result is given through command prompt. How to start building software that deals with graphics..?

    • Alex

      Doing graphics will require either using OS-level functionality, or installing some kind of toolkit or library. If you want to create GUI applications, you can check out QT. If you want to create a graphical application (2d or 3d), check out SDL.

  • Arrays must be constant, are you kidding me? Sure they should when possible, but for a lot of data structures it's necessary to have variable length arrays, take arraylists, merge sort and other algorithms, there you cannot know the array length before compile time. I do believe what was intended is, do not use variable length arrays when you can use a constant length.

    • Alex

      The article meant what it says. :) Standard arrays in C++ must have a constant length. C++ is primitive this way.

      Fortunately, there are workarounds. C++ supports dynamic arrays using operators new and delete (but you have to do the memory management). Most people use a class to abstract the memory management portion away from the user (either via std::vector, or by writing their own templated array classes).

Leave a Reply

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">