Core C++

Lesson 28 : Multi-Dimensional Arrays

In this C++ video tutorial, we covered multi-dimensional arrays. Although not strictly necessary, multi-dimensional arrays offer a convenient way of referring to data in a tabular form.

One of the most common uses for two-dimensional arrays is to store images; the image above of Lena is one of the most commonly used images for benchmarking image processing algorithms. Generally, image data stored with the column and row indices as indicated by the arrows with the bottom left corner being the index [0][0]. The row is designated by the first index and the column is the second index. The pixel values are stored as gray scale vales from 0 to 255.

The small program above declares and initializes a tiny image array of gray scale values and prints the value in row 0 and column 2 (the value is 163). Recall that the unsigned char type takes on values from 0 to 255. So this suits our purposes well. Recall, also that to print the value of a char instead of a character, we need to cast it to an int, as we do here.

The diagram above shows how the two-dimensional array of image data is laid out in memory. When accessing an element of this array, the first index or row offsets the access by four per increment and that second index offsets the access by one. For general multi-dimensional array, the each index offsets the access by the product of all of the later dimension sizes: in a 3x7x5 array the first index offsets by 35 per increment.

 

© 2007–2024 XoaX.net LLC. All rights reserved.