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 54 55
|
#include <iostream>
int main()
{
using array_1d = int[3] ; // type array_1d is an alias for 'array of 3 int'
typedef int array_1d[3] ; // same as above
using array_2d = array_1d[4] ; // type array_2d is an alias for 'array of 4 array_1d'
typedef array_1d array_2d[4] ; // same as above
using array_2d = int[4][3] ; // same as above
typedef int array_2d[4][3] ; // same as above
// a1, a2, a3 all have the same type: 'array of 4 array_1d'
array_2d a1 = { {10,11,12}, { 13,14,15}, {16,17,18}, {19,20,21} } ;
array_1d a2[4] = { {10,11,12}, { 13,14,15}, {16,17,18}, {19,20,21} } ;
int a3[4][3] = { {10,11,12}, { 13,14,15}, {16,17,18}, {19,20,21} } ;
for( int i = 0 ; i < 4 ; ++i ) // for each position in array a1
{
array_1d& row = a1[i] ; // each element of array_2d is of type 'array_1d' or 'array of 3 int'
for( int j = 0 ; j < 3 ; ++j ) // for each position in the array 'row' (which is of type 'array of 3 int')
{
int& value = row[j] ; // each element of row is of type int
std::cout << value << ' ' ;
}
std::cout << '\n' ;
}
std::cout << "--------------\n" ;
// another way of writing the above loop
for( int i = 0 ; i < 4 ; ++i )
{
for( int j = 0 ; j < 3 ; ++j )
{
// a2[i] is the sub-array of a2 at position i
// a2[i][j] is the int at position j of that sub-array
std::cout << a2[i][j] << ' ' ; // print out the value
}
std::cout << '\n' ;
}
array_1d* p1 = a3 ; // implicit conversion from array to pointer to first element
int(*p2)[3] = a3 ; // same as above
array_1d* p3 = &( a3[0] ) ; // same as above
int* p4 = a3[1] ; // implicit conversion from array to pointer to first element
int* p5 = &(a3[1][0]) ; // same as above
p4[1] = 0 ; // subscript operator on pointer
a3[1][1] = 0 ; // same as above
}
|