在C語言中,可以通過以下兩種方式傳入二維數(shù)組:
void myFunction(int arr[][3], int rows, int cols) {
// 函數(shù)體
}
int main() {
int myArray[2][3] = {{1, 2, 3}, {4, 5, 6}};
myFunction(myArray, 2, 3);
return 0;
}
在上面的例子中,myArray
是一個(gè)2行3列的二維數(shù)組,通過myFunction
函數(shù)傳遞給函數(shù)。
void myFunction(int *arr, int rows, int cols) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
int value = *(arr + i * cols + j);
printf("%d ", value);
}
printf("\n");
}
}
int main() {
int myArray[2][3] = {{1, 2, 3}, {4, 5, 6}};
myFunction((int *)myArray, 2, 3);
return 0;
}
在上面的例子中,myArray
數(shù)組首地址被轉(zhuǎn)換為int*
類型,并傳遞給myFunction
函數(shù)。在函數(shù)內(nèi)部,通過指針的形式訪問數(shù)組元素。
這兩種方法都可以傳遞二維數(shù)組給函數(shù),選擇哪種方法取決于實(shí)際情況和個(gè)人偏好。