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 array 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 testScore, 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 testScore 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 testScore[0]. The second is testScore[1]. The tenth is testScore[9]. The last element in our testScore 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 length of the array (between the square brackets) must be a compile-time constant. This is because the length 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 should result because length is not a compile-time constant. Some compilers may allow these kinds of arrays (for C99 compatibility reasons), but they are invalid according to the C++ standard, and should be not be used in C++ programs.

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 length 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
5.x -- Chapter 5 comprehensive quiz

100 comments to 6.1 — Arrays (Part I)

  • Hamed O.Khaled

    Hi Alex!
    I have two questions.
    a) why isn’t good to use define macros variables ?
    b)

    I think it’s not good because the variable x would be resolved in the run time ?? am I right ?
    Thanks!

    • Alex

      1) I cover why macros aren’t good to use in previous chapters -- look up macros in the index and have a read.
      2) x needs to be a compile-time constant, and in this case it isn’t.

  • AS

    what is a run time constant variable? Why is it that in the last case, the array declaration won’t work? Could you please explain this in detail.

    • Alex

      This is a bit hard to explain. When you assign a literal value to a const variable (e.g. const int x = 5), the compiler is smart enough to know that when it sees “x”, it can substitute the value 5. Variable x is a constant, so it will never change. So these kinds of constants have values that are known at compile time.

      On the other hand, in the last example (const int length = temp), we see a const variable initialized with the value of a normal variable. The value of this normal variable isn’t known until runtime -- therefore, the compiler doesn’t know what value the constant will have until runtime either. Therefore, this constant is a runtime constant, not a compile-time constant.

      Fixed arrays must have a compile time constant as a length.

  • Hema

    Suppose I have an array of length 50. What is the easiest way to print the sum of all the elements?

    • Alex

      Use a loop to iterate through the array, so you can access each element. Sum of the value of the elements in a separate variable. Print out the sum.

  • Ahmed

    Thank you for awesome site, keep going great job

  • Mr C++

    This works on CODE::BLOCKS 16.01 successfully.
    even though I input 1 or 0 as the value of (n), it print arr[1] without any error or even any warning.

    • Alex

      Certain compilers will sometimes let you do things that aren’t officially part of the C++ specification. Apparently Code::Blocks will let you do variable length arrays. That doesn’t mean you should use them.

      • Mr C++

        Ok Man ! Thanks !

        But How Is It Printing The 2nd of element of array even if i defined the length to be 1 or 0. That’s Strange !

        • Alex

          You asked it to. Build-in arrays don’t do any bounds checking.

          • Mr C++

            What Do You Mean Here By "Build-In arrays" ?

            • Alex

              The fixed arrays we cover in this lesson.

              • Mr C++

                ok. Thanks. So, If we declare a run-time variable and ask for its value, and, even if it’s smaller(like in the above example), it won’t show any error.

                • Mr C++

                  No, NOT ONLY IN RUN-TIME VARIABLES BUT ALSO COMPILE-TIME VARIABLES.
                  And, One Thing : sizeof(array) still displays the original size and also, the program stops working…
                  Why?

                • Alex

                  I don’t understand the question.

                  C++ doesn’t do bounds checking on fixed arrays. However, it still knows the sizeof the array. If you write something out of bounds of your array, the behavior is undefined.

                • Hardik

                  Ok. Thanks Man ! Can You Tell Me What Is An Initization Function giving an Example?

                • Alex

                • Mr C++

                  But What’s The Point Of Using These Functions ?
                  At First, I Thought It is something like this :-
                  int x = dosomething(x); // x will be INITIALIZED to the return value of the function
                  Plz Explain !

                • Alex

                  To do any initialization your application needs to run.

                • Mr C++

                  Will u tell more about it later in other chapters ? So I Will Wait πŸ˜‰

Leave a Comment

Put C++ code inside [code][/code] tags to use the syntax highlighter