# 如何在C中将2D数组作为参数传递？

2021年3月16日16:25:53 发表评论 465 次浏览

1)当两个维度都全局可用时(作为宏或全局常量)。

``````#include <stdio.h>
const int M = 3;
const int N = 3;

void print( int arr[M][N])
{
int i, j;
for (i = 0; i < M; i++)
for (j = 0; j < N; j++)
printf ( "%d " , arr[i][j]);
}

int main()
{
int arr[][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
print(arr);
return 0;
}``````

``1 2 3 4 5 6 7 8 9``

2)当第二维在全局范围内可用时(作为宏或全局常数)。

``````#include <stdio.h>
const int N = 3;

void print( int arr[][N], int m)
{
int i, j;
for (i = 0; i < m; i++)
for (j = 0; j < N; j++)
printf ( "%d " , arr[i][j]);
}

int main()
{
int arr[][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
print(arr, 3);
return 0;
}``````

``1 2 3 4 5 6 7 8 9``

3)如果编译器兼容C99

``````// The following program works only if your compiler is C99 compatible.
#include <stdio.h>

// n must be passed before the 2D array
void print( int m, int n, int arr[][n])
{
int i, j;
for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
printf ( "%d " , arr[i][j]);
}

int main()
{
int arr[][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int m = 3, n = 3;
print(m, n, arr);
return 0;
}``````

``1 2 3 4 5 6 7 8 9``

4)使用单个指针

``````#include <stdio.h>
void print( int *arr, int m, int n)
{
int i, j;
for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
printf ( "%d " , *((arr+i*n) + j));
}

int main()
{
int arr[][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int m = 3, n = 3;

// We can also use "print(&arr[0][0], m, n);"
print(( int *)arr, m, n);
return 0;
}``````

``1 2 3 4 5 6 7 8 9``

http://www.eskimo.com/~scs/cclass/int/sx9a.html