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";
}
}
In order for your code to work with a 2 dimensional array, the code should be modified such as shown below.
int arr[3][4] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 } };
transpose(&arr, 3, 4);
int** transpose( int(*a)[3][4], 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];
if (i < n && j < m )
{
output[j][i] = (*a)[i][j];
}
}
}
return output;
Look at the parameter declaration int(*a)[3][4]
. It says that the variable a
is a pointer to a 2-dimensional array of size [3][4]. An additional check if (i < n && j < m )
ensures that the array access won't go out of bounds.
It would work without any exception!
First of all in your example m is 3 and n is 4, so in transpose function you are creating output with n (4) pointers but then you have for loop from 0 to m (3), so at this point output already has uninitialized element (output[3]). The reason why it crashes is that you use that uninitialized element in next loops.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.