what can we put in an array

Hello,

Is it possible to have an array where each position of the array is an array?

Thanks!
You could look at a multidimensional array that way.
Yes. That's called a two-dimensional array.

There are two ways to do it:

(1) multidimensional array syntactical sugar

 
int a[ 5 ][ 3 ];

Sometimes, typedefs make life easier, but less direct:
1
2
3
4
typedef int element;
typedef element row[ 3 ];
typedef row table[ 5 ];
table data;

Read more about MD arrays here:
http://www.cplusplus.com/faq/sequences/#what-is-a-md-array

(2) An array of pointers to arrays.

1
2
3
int* a[ 5 ]; // a normal array of pointers to...
for (unsigned n = 0; n < 5; n++)
  a[ n ] = new int[ 3 ];  // ...a dynamic array of integers 

Or:
1
2
3
4
int** a;  // a dynamic pointer to one or more pointers to pointers
a = new (int*)[ 5 ];  // a dynamic array of pointers to...
for (unsigned n = 0; n < 5; n++)
  a[ n ] = new int[ 3 ];  // ...a dynamic array of integers 

(Don't forget to delete stuff when you are done with it.)

All this pointer stuff is a major headache, but useful when handling dynamic data. Like, for example, the lines of a text file. Or database records. Etc. (The reason is, of course, that it is dynamic, meaning that it is not fixed in size like in (1).)

Hope this helps.
Topic archived. No new replies allowed.