Connecting Tech Pros Worldwide Help | Site Map

3d array

Newbie
 
Join Date: Sep 2007
Posts: 1
#1: Sep 3 '07
hi all, i need to knw abt 3d arrays, is it compulsary to specify all the dimensions in 3d array, ex: char [] [] [], whar r the mandataory fields, can we give variable length dimensions for length , width n depth....
Moderator
 
Join Date: Mar 2007
Location: North Bend Washington USA
Posts: 5,366
#2: Sep 3 '07

re: 3d array


Firstly, there are no 3D arrays in C++. There are only one-dimensional arrays. You use the [] operator to define the number of elements:

Expand|Select|Wrap|Line Numbers
  1. int array[3];
  2.  
This is an array of 3 elements. Each element is an int.

Expand|Select|Wrap|Line Numbers
  1. int array[3][4];
  2.  
This is an array of 3 elements. Each element is an array of 4 int. Now some folks may call this a 2D array but it really is a one-dimensional array where the elements are arrays.

Therefore:
Expand|Select|Wrap|Line Numbers
  1. int  array[3][4][5];
  2.  
is an array of 3 elements. Each element is and array of 4 elements each of which is an array of 5 ints.

From this you can deduce the following rules:
1) For a stack array you must specify the number of elements at compile time.
2) For a dynamic array you may specify the number of elements at run time.
3) The name of the array is the address of element 0.

Expand|Select|Wrap|Line Numbers
  1. int array[3];
  2. int* ptr = array; //OK. Element 0 is an int. Hence, "array" is the address of an int
  3. int array1[x];    //ERROR. Number o elements no specified.
  4.  
Expand|Select|Wrap|Line Numbers
  1. int array[3][4]; 
  2. int (*ptr)[4] = array; //OK. Element 0 is an array of 4 int. Hence "array" is the address of an array of 4 int.
  3. int** ptr1 = array;  //ERROR. Element 0 is not the address of hte address of a single int.
  4.  
Expand|Select|Wrap|Line Numbers
  1. int array[3][4][5]; 
  2. int (*ptr)[4][5] = array; //OK. Element 0 is an array of 4 arrays of 5 ints. Hence "array" is the address of an array of 4 elements each of which are arrays of 5 int.
  3. int*** ptr1 = array;  //ERROR. Element 0 is not the address of ther address of the address of a single int.
  4.  
Dynamic allcoations require yout specify the number of elements at run time.
Remember, the number of elments is the first index:
Expand|Select|Wrap|Line Numbers
  1. int num;
  2. cin >> num;
  3. int* array = new int[num];           //OK
  4. int (*ptr)[4] = new int[num][4];     //OK
  5. int (*ptr)[4][5]  = new int[num][4][5];  //OK
  6.  
Reply