Passing Multidimensional Array to Function in C
In this code snippet, an attempt is made to pass a C-style multidimensional array to a function that expects an array of integer pointers:
#include<stdio.h> void print(int *arr[], int s1, int s2) { ... } int main() { int a[4][4] = {{0}}; print(a,4,4); }
This code compiles in C but not in C . Here's why:
print(&a[0],4,4);
In C , this decay is not allowed. The array type int4 is not implicitly convertible to the pointer type int**. This explains the error message:
cannot convert `int (*)[4]' to `int**' for argument `1' to `void print(int**, int, int)'
Solution:
To pass a multidimensional array to a function in C , one must explicitly convert it to a pointer of the appropriate type. This can be achieved using the following technique:
#include<stdio.h> void print(int **arr, int s1, int s2) { ... } int main() { int a[4][4] = {{0}}; print((int **)a,4,4); }
By explicitly converting the array to a pointer using the (int )** cast, the code now compiles and behaves as intended in both C and C .
The above is the detailed content of How Can I Correctly Pass a Multidimensional Array to a Function in C ?. For more information, please follow other related articles on the PHP Chinese website!