I am having problems declaring a pointer into my 4d array.
I have declared it like this:
int matrix[7][4][5][5] =
{
{/* Section 1 */
{
/* 1st */
{0,0,1,0,0},
{0,0,1,0,0},
{0,0,1,0,0},
{0,0,0,0,0},
{0,0,0,1,0}
},
{
/* 2nd */
{0,0,0,0,0},
{0,0,0,0,0},
{1,0,0,1,1},
{0,0,0,0,0},
{0,0,0,0,0}
},
. . .
}/* End Section 1 */
}
I would like to be able to print out the elements in the 2d array underneath the comment /* 2nd */.
I had some code to loop through a 2d array like this:
for(int i = 0; i < 5; i++)
{
for(int j=0; j<5; j++)
{
std::cout << " " << pMatrixPtr[i][j];
}
std::cout << "\n";
}
But my problem is – I don’t know what to set pMatrixPtr to, or what type it should be (I mean levels of pointer . . . should it be **? ). Nothing I try seems to compile, and I think it’s because I don’t fully understand what types are involved.
Can anyone explain how a 4d array can be accessed via a pointer, and what that pointer should point to?
will set
pMatrixPointerto point to the second 2D array inmatrix. You would then use it as in your code above:Why this works:
In most contexts, an expression of array type will be converted to an expression of pointer type, and the value of the expression will be the address of the first element in the array (this is true for both C and C++).
The expression
matrix[0][1]has type “5-element array of 5-element array ofint“; by the rule above, the expression is converted to type “pointer to 5-element array ofint” (int (*)[5]) and the value is&matrix[0][1].The expression
a[i]is equivalent to*(a + i); there’s an implicit dereference in the subscript operation. SopMatrix[i]is equivalent to*(pMatrix + i), which yields a pointer value that we further offset withj, as*(*(pMatriux + i) + j).