Source Code. Projects. Nerd Stuff. Art Stuff.

Lesson 7: Multi-Dimensional Arrays

Multi-Dimensional Arrays

Multidimensional Arrays (Section 10.5)

  • A muti-dimensional array is really an array of arrays. You can also think of it as a matrix of values.
  • For example, you might use a two-dimensional array of ints to store the color value for each pixel on your screen (although this the real screen color is stored as three values: brightness of red, green, and blue) :
      int pixels[480][640];

    To set the pixel in the position (3, 5) (meaning row #3, column #5) to the value 7 you would type:

      pixels[3][5] = 7;

    To access the one-dimensional array of ints on row number 10, use:

  • For another example, imagine you want to store the last names of the students in this class in an array of cstrings. Since a cstring is an array, an array of cstrings is an array of arrays — a two- dimensional array. If there are 40 students in the class, and we limit last names to 20 letters (21 chars including the null) then the array would be declared with the following:
      char lnames[40][21];

    To output the first student’s last name, we would type:

      cout << lnames[0];
  • For a function to accept an entire multi-dimensional array as a parameter, we must specify all but the first dimension. This way, the function can look at it as a one-dimensional array whose elements are of known size. To go back to the pixels example, the following function would clear the screen:
        void clearScreen(int p[][640], int size1)
          int x, y;
          for (y=0; y < size1; y++)
            for (x=0; x < 640; x++)
              p[y][x] = 0;

    We would call the above function with the following function call:

      clearScreen(pixels, 480);
  • Here is a complete program using the pixels example above
  • And here is a program which removes duplicates from an array of cstrings