溫馨提示×

c語言怎么傳入二維數(shù)組

小億
93
2024-08-17 08:56:36
欄目: 編程語言

在C語言中,可以通過以下兩種方式傳入二維數(shù)組:

  1. 作為函數(shù)參數(shù)傳遞:可以將二維數(shù)組作為函數(shù)的參數(shù)傳遞給函數(shù)。在函數(shù)定義時(shí),需要指定數(shù)組的行數(shù)和列數(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ù)。

  1. 使用指針傳遞:可以將二維數(shù)組的首地址作為指針傳遞給函數(shù),然后在函數(shù)內(nèi)部通過指針的形式來訪問數(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è)人偏好。

0