Parameter passing with two-dimensional array names
Segmention Error occurs when two-dimensional array names are used as parameters. This is because it cannot properly address elements in a two-dimensional array. The correct method is as follows:
#include
#include
#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. Pass the two dimensions of a two-dimensional array in the form of Variables
As follows:
[Cpp]View plaincopyprint?
- # Include
- # Include
-
- # 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 );
- }
In this case, the sub-function cannot access the array elements in the form of a [I] [j], because the array elements are stored sequentially and the addresses are continuous, when an array element is accessed using a [I] [j], the specified element cannot be accessed sequentially. All elements can only be accessed by computing the specified element.
2. Use a pointer variable pointing to a one-dimensional array, as shown in the following example:
#include
#include
#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)); //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(a, 2, N); }
Int (* a) [N] indicates the pointer variable pointing to the one-dimensional array. That is, the object that a points to is an array containing four integer elements. Note:
Int * a [N] indicates that there is a one-dimensional array a [N]. All elements in this array are (int *) elements.
Here, you can use a [I] [j] Or * (a + I) + j) to access elements in a two-dimensional array in a subfunction)
In this case (* (a + I) [j], a [I * n + j]);, * (a + I) + j ), a [I] [j], * (int *) a + I * n + j) can be accessed.