void displayMatrix(int **ptr)
{
printf("%d %d \n",**ptr,*(*ptr+1));
*ptr++;
printf("%d %d \n",**ptr,*(*ptr+1));
}
Is it a correct way to pass 2x2 array to function ?
displayMAtrix(array);
void displayMatrix(int **ptr)
{
printf("%d %d \n",**ptr,*(*ptr+1));
*ptr++;
printf("%d %d \n",**ptr,*(*ptr+1));
}
Is it a correct way to pass 2x2 array to function ?
displayMAtrix(array);
If you have a 2D array with automatic storage duration (e.g. int matrix[2][2];
), then no, this is not the correct way to pass a 2D array.
int f ( int, char ** )
{
int matrix[2][2];
displayMatrix(matrix);
}
To be standard compliant (there are other ways to make it work, but this is the standard, recommended way), you need to declare displayMatrix()
as:
void displayMatrix ( int matrix[][2] );
You must declare the size of each dimension (possibly excluding the first). The reason behind this lies with the way 2D arrays are stored in memory. Wikipedia has a decent article on row-major order explaining the layout.
If you're allocating large matrices (e.g. for storing images), you'll usually end up with double pointers because you'll be allocating the memory differently. In this case, you usually have a 1D array of pointers with each item storing the pointer to a 1D array representing rows (or columns).
In that case, you would get something like:
// this function is over-simplified. it may leak memory if any
// but the first `new` throws `std::bad_alloc`.
int ** new_matrix ( int m, int n )
{
int ** matrix = new int*[m];
for (int i = 1; (i < m); ++i ) {
matrix[i] = new int[n];
}
return (matrix);
}
void displayMatrix ( int ** matrix, int m, int n );
int main ( int, char ** )
{
int **const matrix = new_matrix(2, 2);
displayMatrix(matrix, 2, 2);
}
This is one of the reasons multidimensional raw arrays are so awkward in C++. If you know at least the last dimension of the array, you can do it this way:
void displayMatrix(int array[][2])
{
// code goes here
}
The int**
approach only works for dynamically sized arrays that were declared that way. It's not interchangeable with a int[2][2]
array. For more info on the right way (i.e., when you're not doing a homework assignment) to do this, you can look at this SO question.
I would do it like this:
struct Array2d {
float *array;
int size_x;
int size_y;
};
void myfunction(Array2d &a) { a.array[x+y*a.size_x] = 10.0; }
Use a vector if you can help it
void displayMatrix(const std::vector<int> &dat);
If that fails, don't use arrays of arrays if you can help it. Calculate the offsets yourself.
void displayMatrix(int *dat);
If you intend to legitimately pass arrays of arrays, you have to specify the size of the arrays except for the largest dimension. It seems others have answered this before I could type it out.