Discussion Locked

Arrays in C++

0 helpful
7 replies
Closed to new repliesThis discussion is closed. It stays readable, but it takes no new replies.
I'm a student and I'm trying to understand arrays and how to use them. In particular I have a problem that could be solved with 3 separate arrays (how to tie them together?) or one 3-dimensional array. Any ideas as to how to do this or where to get information would be greatly appreciated!

7 replies

by softech

using a 3-dimensional array is fine.

int temp[3][size_of_each];

or you can use a structure:

//--------------
struct Person
{ int info1[10];
int info2[10];
int info3[10];
};

Person temp;

temp.info1[0] = 1;
temp.info2[0] = 2;
/* etc */
//----------------------

by pvp

Tying 3 arrays together is easy--just use the same subscript value for each:

int x[3], y[3], z[3], subscr, xx, yy, zz;

subscr = 1; /* valid range: 0-2 */

xx = x[subscr];
yy = y[subscr];
zz = z[subscr];

Incidentally, with only one dimension, it's a vector, not an array!

For a single 3-dimension array:

int d3[3][3]; /* same number of ints as above */
int xx, yy, zz, rowsubscr, colsubscr;

In memory, ascending int-size addresses contain x[0], x[1], x[2] in the 3-vector solution; for the array: d3[0][0], d3[0][1], d3[0][2], d3[1][0], d3[1][1], d3[1][2], d3[2][0], d3[2][1], d3[2][2].

rowsubscr = 1; /* still valid range 0-2 */
colsubscr = 0;

xx = d3[rowsubscr][colsubscr];
colsubscr++; /* is now 1 */

yy = d3[rowsubscr][colsubscr];
colsubscr++; /* is now 2 */

zz = d3[rowsubscr][colsubscr];
colsubscr++; /* is now 3 and out of range */

by jhurley

Think about the squares on a piece of graph paper.

A 1-D array "float name[size];" is like a single row of squares on the graph paper were each square conatins a value.

A 2-D array "float name[size1][size2];" is like the whole sheet of graph paper with values in all the squares

A 3-D array "float name[size1][size2][size3];" is like a stack of graph paper were all the squares can contain a value.

It sounds like what you really need is a 2-D array like so:

name_of_array[3][size_of_single array]

can be any valid data type ie int, float, double, ...

Hope that helps.

This discussion is closed to new replies.