C-Style Arrays

One of the most common data structures, especially for scientific and numerical programming, is a group of variables all of the same type. This is frequently called an array.

Terminology

A scalar is a single item (real/float, integer, character/string, complex, etc.) An array contains data of the same type with each scalar element addressed by indexing into the array. An array has one or more dimensions . The bounds are the lowest and highest indexes. The rank is the number of dimensions.

A C-style array is nothing more than a block of memory that can be interpreted as an array; it is not a defined data type. Other options are available in class libraries.

Arrays must be declared by type and either by size or by some indication of the number of dimensions.

float a[100];
int M[10][10];

If a variable is used, it must be a const

const int N=10;
float z[N];

The starting index is always 0, so for a 100-element array the items are numbered 0 to 99.

Orientation

Elements of an array are arranged linearly in memory no matter how many dimensions you declare. If you declare a 3x2 array the order in memory is

(1,1), (1,2), (2,1), (2,2), (3,1), (3,2)

“Orientation” refers to how the array is stored in memory , not to any mathematical properties. C++ and most other languages are row-major oriented. Some (Fortran,Matlab, R) are column-major oriented. Loop indices should reflect this whenever possible (when you need loops). Move left to right. A(i,j,k)loop order isdo for i/for j/for k

Initializing Arrays in C++

Arrays can be initialized when created using a constructor:

   float A[3]={10.,20.,30.}

Curly braces are required.

Example:

#include <iostream>
using namespace std;
int main(){

    const int n=5;
    float A[n]={10.,20.,30.,40.,50.};

    for (int i=0;i<n;i++) {
        cout<<A[i]<<" ";
    }
    cout<< "\n";
    return 0;
}

Elements not explicitly initialized will be set to 0. Try it: In the above program, change the initialization to

float A[n]={};

Allow it to print the output. Then try

float A[n]={10.,20.,30.};

(i.e. setting only three out of five) with no other changes to the program.

WARNING

C++ happily lets you “walk off” your array. Most commonly this occurs when you attempt to access an element outside of the declared size. For instance, in C++ an index of -1 will never be legal, but for ordinary C-style arrays it will not check if your program attempts to access a value like A[-1]. It is also commmon, especially in loops, to try to access an element beyond the last one. Do not forget that array indices are 0-based, so the last element of an array of size N will be N-1.

An error of this type usually results in a segmentation violation, or sometimes garbage results.

Example: in your previous code change

cout<< A[i]<<"";

To

cout<< A[i+1]<<" ";

Multidimensional Arrays in C++

Multidimensional arrays are just “arrays of arrays” in C++. They are declared with multiple brackets:

float A[2][5];

Elements are referenced like

A[0][2]
A[i][j]

Small arrays can be initialized as follows:

A={{1.,2.,3.,4.,5.},{6.,7.,8.,9.,10.}};

Exercise Write a program to:

  • Declare an integer array of 10 elements In your program:
    • Print the size of the array
    • Change the fourth element to 11

Declare a real array of rank 2 (two dimensions) and allocate it with new. Allocate the array and set each element to the sum of its row and column indices.

Example Solution

#include <iostream>

using namespace std;

int main() {
    int a[10];
    int size = sizeof(a)/sizeof(a[0]);
    cout << size << "\n";
    a[3]=11;
    for (int i=0; i<size; ++i) {
        cout << a[i] << " ";
    }
    cout << "\n\n";

    int m=4, n=5;
    float **A;
    A=new float*[n];
    for (int i=0; i<m; ++i) {
        A[i]=new float[n];
    }
    for (int i=0; i<m; ++i) {
        for (int j=0; j<n; ++j) {
            A[i][j] = i+j;
        }
    }
    for (int i=0; i<m; ++i) {
        for (int j=0; j<n; ++j) {
            cout << A[i][j] << " ";
        }
        cout << "\n";
    }
}

Previous
Next