Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
C++ Fundamentals

You're reading from   C++ Fundamentals Hit the ground running with C++, the language that supports tech giants globally

Arrow left icon
Product type Paperback
Published in Mar 2019
Publisher
ISBN-13 9781789801491
Length 350 pages
Edition 1st Edition
Languages
Arrow right icon
Authors (2):
Arrow left icon
Antonio Mallia Antonio Mallia
Author Profile Icon Antonio Mallia
Antonio Mallia
Francesco Zoffoli Francesco Zoffoli
Author Profile Icon Francesco Zoffoli
Francesco Zoffoli
Arrow right icon
View More author details
Toc

Table of Contents (9) Chapters Close

C++ Fundamentals
Preface
1. Getting Started FREE CHAPTER 2. Functions 3. Classes 4. Generic Programming and Templates 5. Standard Library Containers and Algorithms 6. Object-Oriented Programming 7. Appendix

Arrays


An array is a data structure containing a series of elements of the same type that have been placed in contiguous memory locations that can be individually accessed by their position.

Arrays have fixed sizes and cannot be extended; this contributes to their runtime performance, with a cost in terms of limited flexibility.

Array Declaration

Like any other variable, arrays need to be declared before they can be used. An array declaration has the following form:

type name [elements];

Here, type is the type of the contained elements, name is the identifier of the array variable, and elements is the length of the array, so it signifies the number of elements contained within.

The term elements needs to be a constant expressions that is known at compile time, since that is the time when the array size is evaluated to determine the dimension of the block of static memory to allocate.

When an array is declared, its content is left undetermined, which means that the elements are not set to any specific value. This is often confusing for programmers as you might expect that the elements are initialized to the default value for the array type.

Array Initialization

Array elements can be specifically initialized at declaration time by enclosing these initial values in braces:

int foo [5] = { 1, 2, 11, 15, 1989 };

When we initialize a list array, we can also omit its length as it will be determined by the number of values provided. The following declaration is equivalent to the previous one:

int foo [] = { 1, 2, 11, 15, 1989 };

If the number of elements is provided, but the array is initialized with fewer elements, then the remaining value will be zero-initialized, for example:

int foo [5] = { 1, 2, 11 };

The previous code is equivalent to the following:

int foo [5] = { 1, 2, 11, 0, 0 };

Accessing the Values of an Array

The values of an array can be accessed in the same way as any other values of the same type. The following is the syntax to access an array:

name[index]

An element of an array can be accessed to store a new element or to read its value.

For example, the following statement updates the value at position 4 of the previously declared array named foo:

foo [4] = 15

The following is used to copy the content of the element at position 2 into a new variable:

int x = foo [2]

It is important to notice that the elements at positions 4 and 2 refer to the fifth and third elements, respectively. This is due to the fact that indexing starts from 0. The following diagram illustrates how index entries work in arrays:

Figure 1.9: Initializing a one-dimensional array

Exceeding the valid range of indices for an array is syntactically correct, so the compiler will not produce any errors. Accessing an array out of bounds in C++ is considered an undefined behavior, which means that the code's behavior is not prescribed by the language specification. This can result in runtime errors such as bugs caused by access to an unallocated location in memory or program termination (segmentation fault) due to an attempt to access memory not owned by the program.

Multidimensional Arrays

Multidimensional arrays are commonly described as arrays of arrays, where an array's elements are other arrays.

The following syntax illustrates a bi-dimensional array:

type name [n][m];
int bi_array [3][4]

Here, n is the dimension of the array and m is the dimension of its elements.

Typically, in a bi-dimensional array like the previous one, the first dimension is referred to as the row and the second one is referred to as the column.

Multidimensional arrays are not limited to two dimensions; they can have as many dimensions as needed, but keep in mind that the memory that's used increases exponentially with each dimension. Similar to one-dimensional arrays, multidimensional arrays can be initialized by specifying a list of initializers, one for each row. Let's examine the following code:

#include <iostream>
int main()
{
  int foo [3][5] = {{ 1, 2, 11, 15, 1989 }, { 0, 7, 1, 5, 19 }, { 9, 6, 131, 1, 2 }};
  for (int x = 0; x < 3; x++) 
  { 
    for (int y = 0; y < 5; y++) 
    {
      std::cout <<"Array element at [" << x << "]" << "[" << y << "]: "<< foo[x][y] << std::endl;
    }
  }
}
Output:
Array element at [0][0]: 1
Array element at [0][1]: 2
Array element at [0][2]: 11
Array element at [0][3]: 15
Array element at [0][4]: 1989
Array element at [1][0]: 0
Array element at [1][1]: 7
Array element at [1][2]: 1
Array element at [1][3]: 5
Array element at [1][4]: 19
Array element at [2][0]: 9
Array element at [2][1]: 6
Array element at [2][2]: 131
Array element at [2][3]: 1
Array element at [2][4]: 2

Alternatively, since the compiler can infer the length of the internal arrays from the definition, the nested braces are optional and provided only for readability:

int foo [3][5] = {1, 2, 11, 15, 1989, 0, 7, 1, 5, 19, 9, 6, 131, 1, 2};

Activity 2: Defining a Bi-Dimensional Array and Initializing Its Elements

In this section, we will define a bi-dimensional array (3x3) of type integer and write a program to assign each element the addition of their corresponding index entries in the array:

  1. Define an array of integers of size 3x3.

  2. Iterate over each element of the array using a nested for loop and assign the product values x and y to the index.

Note

The solution for this activity can be found on page 282.

You have been reading a chapter from
C++ Fundamentals
Published in: Mar 2019
Publisher:
ISBN-13: 9781789801491
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime