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 2×2 array to function ?
displayMAtrix(array);
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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.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: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.
Alternate storage type
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: