1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 | #include <stdio.h>
#include <stdlib.h>
int main(int argc, char* argv[]) {
// Declare and initialize an array with 2 "rows" and 3 "columns".
int array_3d[2][3][4] = {
{ // begin array_3d[0][…][…]
{100, 101, 102, 103}, // begin array_3d[0][0][…]
{104, 105, 106, 107}, // begin array_3d[0][1][…]
{108, 109, 110, 111} // begin array_3d[0][2][…]
},
{ // begin array_3d[1][…][…]
{112, 113, 114, 115},
{116, 117, 118, 119},
{120, 121, 122, 123}
}
};
// Could also work with all but the first dimension specified in declaration.
// int array_3d[][3][4] = { // OKAY
// KEY POINT: In memory, array_flat will be the same as array_3d
int array_flat[24] = { //
100, 101, 102, 103,
104, 105, 106, 107,
108, 109, 110, 111,
112, 113, 114, 115,
116, 117, 118, 119,
120, 121, 122, 123
};
// If I give you code that accesses a multi-dimensional array,
// you should be able to give a declaration and initialization
// that would make that code work.
printf("array_3d[0][2][3] ======================== %d\n",
array_3d[0][2][3]);
printf("array_flat[(0 * 3 * 4) + (2 * 4) + (3)] == %d\n",
array_flat[(0 * 3 * 4) + (2 * 4) + (3)]);
// would not have worked with...
// int array[6][4] // BROKEN
return EXIT_SUCCESS;
}
/*
OUTPUT:
array_3d[0][2][3] ======================== 111
array_flat[(0 * 3 * 4) + (2 * 4) + (3)] == 111
*/
/* vim: set tabstop=4 shiftwidth=4 fileencoding=utf-8 noexpandtab: */
|
© Copyright 2017 Alexander J. Quinn This content is protected and may not be shared, uploaded, or distributed.