I thought I was OK at C style arrays, apparently not. I can't figure this out.
Say I declare a function
void RotateMatrix(int ** matrix, int n)
{
auto x = matrix[0][0];
}
(assume matrix is square). Driving it from the main function
void main()
{
int matrix[4][4] =
{
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12},
{13, 14, 15, 16}
};
RotateMatrix((int**) matrix, 4);
}
Basically, matrix[0][1]
results in a buffer overflow. Debugging it, matrix[0][0]
tries to go to the address 0x0000000200000001
, a combination of the first 8 bytes in the array, presumably as int is 4 bytes and int*
is 8 bytes, and int**
is a pointer to a pointer of ints, hence it treats the first 2 matrix entries as int*
. However, this confused me as answers like bobobobo's on How to pass a multidimensional array to a function in C and C++ seems to show you can use the int**
approach. I'm confused. I've seen other SO posts say the same thing, so why does it work for them?
I thought matrix[0][0]
it would do matrix[0]
's address plus offset 0 * sizeof(int)
(which would still be the first element)