In the following code when arr is passed to transpose function as below and inspect the contents of a as a[0], it is giving 0x00...001 but not the original address as inspected for arr, why it is so and what is wrong ?. I expect a[0] to be the address of 1 in the array and a[0][1] to be the first element of the array. Please explain.
problem:
int arr[][4] = { { 1, 2, 3, 4},{ 5, 6,7,8 },{ 9,10,11,12 } };
transpose((int **)arr, 3, 4);
int** transpose(int** a, int m, int n)
{
int** output = new int*[n];
for (int i = 0;i < m;i++)
{
output[i] = new int[n];
}
for (int i = 0;i < m;i++)
{
for (int j = 0;j < n;j++)
{
//*((output[j]) + i) = *(a[i] + j);
//*((output[j]) + i) = a[i][j];
output[j][i] = a[i][j];
}
}
return output;
}
throwing exception.
works fine:
int** output=transpose((int *)arr, 3, 4);
print(output,3,4);
int**transpose(int * a, int m, int n)
{
int** t = new int*[n];
for (int i = 0;i < n;i++)
{
t[i] = new int[m];
}
for (int i = 0;i < m;i++)
{
for (int j = 0;j < n;j++)
{
t[j][i] = *((a + i*n) + j);
}
}
return t;
}
void Matrix::print(int ** a, int m, int n)
{
for (int i = 0;i < m;i++)
{
for (int j = 0;j < n;j++)
{
std::cout << a[i][j] << ",";
}
std::cout << "\n";
}
}