Segmention error is prone to occur when passing a two-dimensional array name as a parameter. This is because the problem of addressing elements in a two-dimensional array is not correct, and the correct method is as follows:
#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. Pass the two dimensions of the two-dimensional array to the past in the form of a variable
is as follows :
[CPP]View Plaincopyprint?
- < Span class= "Preprocessor" style= "margin:0px; padding:0px; Border:none; Color:gray; Background-color:inherit "> #include <stdlib.h> &NBSP;&NBSP;
- < Span class= "Preprocessor" style= "margin:0px; padding:0px; Border:none; Color:gray; Background-color:inherit "> #include <stdio.h> &NBSP;&NBSP;
-
- #define N 4
- voidTestarray (int**a,intm,intN)
- {
- for ( int i = 0; i < m; ++i)
- for ( int &NBSP;J&NBSP;=&NBSP;0;&NBSP;J&NBSP;<&NBSP;N;&NBSP;++J)
-
- " a[%d][%d] = %d\n " , i, j, * (( int *) A &NBSP;+&NBSP;I&NBSP;*&NBSP;N&NBSP;+J));
- }
- }
-
- < Span class= "Datatypes" style= "margin:0px; padding:0px; Border:none; Color:rgb (46,139,87); Background-color:inherit; Font-weight:bold ">int main ()
- {
- int a[2][n] = {{1, 2, 3, 4}, {5, 6, 7, 8}};
-
- int **) a, 2, n);
- }
In this case, the array element cannot be accessed using a[i][j] in the child function, because the array elements are stored sequentially, the address is contiguous, and when the array element is accessed using A[I][J], the specified element cannot be accessed sequentially, all of which we can only compute by specifying the element to be accessed.
2. Use pointer variables pointing to a one-dimensional array, as shown in the following example:
#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)); 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] represents a pointer variable that points to a one-dimensional array, that is, the object pointed to by a is an array of 4 integral elements. Note () should not be less, if defined as:
int *a[n] Indicates that there is a one-dimensional array a[n], and all elements in the array are elements of type (int *).
Here, you can access the elements in a two-dimensional array in a child function using A[I][J] or * (* (a+i) +j)
In this case (* (a+i)) [J],a [i * n +j]), * (* (a+i) +j), a[i][j],* ((int*) A + i * n +j) can be accessed.
Parameter transfer problem for two-dimensional array names