Two Dimensional Arrays in C++
Arrays and pointers have a close relationship. As we will soon see, an array in C++, is basically a constant pointer.
Ways to create Single Dimensional Arrays in C++
- int arr[10]
- int arr[3] = {1,2,3}
- int arr[] = {1,2,3} when you use an initializer list you don't need to include the size in the brackets
Example of declaring a two dimensional array
You must specifiy the column value for array.
const int ROWS =3;
const int COLS = 3;
//declare a two dimensional array named matrix
int matrix[ROWS][COLS];
//populate with random numbers
for(i =0;i< ROWS; i++)
for(j= 0;j < COLS; j++)
matrix[i][j] = rand() % 100;
Passing Double Arrays two Functions
void printOut2D(int x[][COLS], int rows){
}
}
Pointers and Double Arrays
Download the code below and run it. WHen you create a pointer two a double array of ints with 3 rows and 4 columns you're really creating a pointer to an array of 4 ints (number of columns)
const int ROWS =3;
const int COLS = 4;
// create the douible array
int matrix[ROWS][COLS];
int i,j;
for(i =0;i< ROWS; i++)
for(j= 0;j<COLS; j++)
matrix[i][j] = rand() % 100;
//a pointer to COLS number of ints
// if COLS is 4 this is a pointer to
// an array of 4 ints
int (*ptr)[COLS] = matrix;
for(int i =0;i< ROWS; i++){
for(int j= 0;j<COLS; j++)
cout<<ptr[i][j] << " ";
cout<<endl;
}