二维数组作为参数需要注意的问题

来源:互联网 发布:音乐唱歌软件 编辑:程序博客网 时间:2024/05/17 16:53

在用二维数组名作为参数传递时容易出现Segmention Error。这是因为不能正确为二维数组中元素寻址的问题,正确的方法如下:

1. 用指向一维数组的指针变量,如下例子所示:

[cpp] view plain copy
 print?
  1. #include <stdlib.h>  
  2. #include <stdio.h>  
  3.   
  4. #define N   4  
  5.   
  6. void testArr(int (*a)[N], int m)  
  7. {  
  8.     for(int i = 0; i < m; ++i)  
  9.         for(int j = 0; j < N; ++j)  
  10.         {  
  11.             printf("a[%d][%d] = %d\n", i, j, a[i][j]);  
  12.         }  
  13. }  
  14.   
  15. int main()  
  16. {  
  17.     int a[2][N] = {{1, 2, 3, 4}, {5, 6, 7, 8}};  
  18.     testArr(a, 2);  
  19. }  

int (*a)[N] 表示指向一维数组的指针变量,即a所指向的对象是含有4个整型元素的数组。注意 () 不能少,若定义成:

int *a[N] 则表示有一个一维数组a[N],该数组中的所有元素都是 (int *)类型的元素。

在这里,在子函数中访问二维数组中的元素可以用 a[i][j] 或者 *(*(a+i)+j)


2. 将二维数组的两个维度用变量的形式传递过去

如下所示

[cpp] view plain copy
 print?
  1. #include <stdlib.h>  
  2. #include <stdio.h>  
  3.   
  4. #define N   4  
  5. void testArray(int **a, int m, int n)  
  6. {  
  7.     for(int i = 0; i < m; ++i)  
  8.         for(int j = 0; j < n; ++j)  
  9.         {  
  10.             printf("a[%d][%d] = %d\n", i, j, *((int*)a + i * n +j));  
  11.         }  
  12. }  
  13.   
  14. int main()  
  15. {  
  16.     int a[2][N] = {{1, 2, 3, 4}, {5, 6, 7, 8}};  
  17.   
  18.     testArray((int **)a, 2, N);  
  19. }  


此时在子函数中不能使用a[i][j]的形式访问数组元素,因为数组元素都是顺序存储,地址连续,在使用a[i][j]访问数组元素时,无法顺序访问到指定的元素,所有我们只能通过计算指定所要访问的元素。

0 0