在用二维数组名作为参数传递时容易出现Segmention Error。这是因为不能正确为二维数组中元素寻址的问题,正确的方法如下:
-
#include <stdlib.h>
-
#include <stdio.h>
-
-
#define N 4
-
void testArray(int *a, int m, int n)
-
{
-
for(int i = 0; i < m; ++i)
-
for(int j = 0; j < n; ++j)
-
{
-
printf("a[%d][%d] = %d\n", i, j, *(a+i*n+j));
-
}
-
}
-
-
int main()
-
{
-
int a[2][N] = {{1, 2, 3, 4}, {5, 6, 7, 8}};
-
-
testArray((int *)a, 2, N);
-
}
1. 将二维数组的两个维度用变量的形式传递过去
如下所示:
-
#include <stdlib.h>
-
#include <stdio.h>
-
-
#define N 4
-
void testArray(int **a, int m, int n)
-
{
-
for(int i = 0; i < m; ++i)
-
for(int j = 0; j < n; ++j)
-
{
-
printf("a[%d][%d] = %d\n", i, j, *((int*)a + i * n +j));
-
}
-
}
-
-
int main()
-
{
-
int a[2][N] = {{1, 2, 3, 4}, {5, 6, 7, 8}};
-
-
testArray((int **)a, 2, N);
-
}
此时在子函数中不能使用a[i][j]的形式访问数组元素,因为数组元素都是顺序存储,地址连续,在使用a[i][j]访问数组元素时,无法顺序访问到指定的元素,所有我们只能通过计算指定所要访问的元素。
2、用指向一维数组的指针变量,如下例子所示:
-
#include <stdlib.h>
-
#include <stdio.h>
-
-
#define N 4
-
void testArray(int (*a)[4], int m, int n)
-
{
-
for(int i = 0; i < m; ++i)
-
for(int j = 0; j < n; ++j)
-
{
-
printf("a[%d][%d] = %d\n", i, j, *(*(a+i)+j));
-
}
-
}
-
-
int main()
-
{
-
int a[2][N] = {{1, 2, 3, 4}, {5, 6, 7, 8}};
-
-
testArray(a, 2, N);
-
}
int (*a)[N] 表示指向一维数组的指针变量,即a所指向的对象是含有4个整型元素的数组。注意 () 不能少,若定义成:
int *a[N] 则表示有一个一维数组a[N],该数组中的所有元素都是 (int *)类型的元素。
在这里,在子函数中访问二维数组中的元素可以用 a[i][j] 或者 *(*(a+i)+j)
在这种情况下(*(a+i))[j],a [i * n +j]);,*(*(a+i)+j),a[i][j],*((int*)a + i * n +j)都可以进行访问。二维数组名如何作为参数传递
原文:http://blog.csdn.net/u014082714/article/details/45071791