50 multidimensional array (two-dimensional array)

1. Definitions: Syntax: type array name [size] [size]  

  Such as: int a [2] [3]

2, in the form of a two-dimensional memory array, each element address is continuously distributed, i.e. on the basis of the previous element plus 4 (int bytes)

. 1  void main () {
 2      int A [ . 5 ] [ . 6 ];   // not initialized, then memory is allocated garbage value
 . 3  
. 4      // all initialized to 0 
. 5      for ( int I = 0 ; I < . 5 ; I ++ ) {
 . 6          for ( int J = 0 ; J < . 6 ; J ++ ) {
 . 7              A [I] [J] = 0 ;
 . 8          }
 . 9      }
 10  
. 11      A [ . 1 ] [ 2 ] =. 1 ;
 12 is      A [ 2 ] [ . 1 ] = 2 ;
 13 is      A [ 2 ] [ . 3 ] = . 3 ;
 14  
15      // output two-dimensional array 
16      for ( int I = 0 ; I < . 5 ; I ++ ) {
 . 17          for ( int J = 0 ; J < . 6 ; J ++ ) {
 18 is              the printf ( " % D   " , A [I] [J]);
 . 19          }
 20 is         the printf ( " \ n- " );
 21 is      }
 22 is  
23 is      // view layout of a two-dimensional array 
24      the printf ( " first address two-dimensional array: P% \ n- " , A);
 25      the printf ( " first address two-dimensional array : P% \ n- " , a [ 0 ]);
 26 is      the printf ( " first address two-dimensional array: P% \ n- " , & a [ 0 ] [ 0 ]);
 27  
28      // two-dimensional array of individual elements an address output 
29      for ( int I = 0 ; I < . 5 ; I ++ ) {
30         for (int j = 0;j < 6;j++) {
31             printf("a[%d][%d]的地址=%p   ", i, j, &a[i][j]);
32         }
33         printf("\n");
34     }
35 }

 

 3, two-dimensional array of memory layout diagram

 

 

4, direct two-dimensional array initialization

  ① type array name [size] [size] = {{value 1, value 2 ......}, {value 1, value 2 .......}, {value 1, value 2 ... ......}}

    

  ② type array name [size] [size] = {value 1, value 2 and value 3, value 4, value 5, the value ........ 6}

    

 

 5, use the flexible way to traverse the array as follows: and get and

  int  map[3][3] = { {0,0,1} , {1,1,1} , {1,1,3 } } ;

 1 void main() {
 2     int map[3][3] = { {0,0,1},{1,1,1},{1,1,3} };
 3 
 4     //1,先得到行
 5     int rows = sizeof(map) / sizeof(map[0]);
 6 
 7     //2,得到列
 8     int cols = sizeof(map[0]) / sizeof(int);
 9     
10     int sum = 0;
11     for (int i = 0;i < rows;i++) {
12         for (int j = 0;j < cols;j++) {
13             printf("%d  ", map[i][j]);
14             sum += map[i][j];
15         }
16         printf("\n");
17     }
18     printf("sum=%d\n", sum);
19 }

 

 6,二维数组细节

  ①可以只对部分元素赋值,未赋值的元素自动取“零”值,

    

 

       

 

   ②如果对全部元素赋值,那么第一维的长度可以不给出

  ③二维数组可以看作是由一维数组嵌套而成的,如果一个数组的每个元素又是一个数组,那么它就是二维数组。

    二维数组 a[3][4] 可以看作三个一维数组,他们的数组名分别为 a[0]  a[1]  a[2] ,这三个一维数组都有4个元素

  

 

Guess you like

Origin www.cnblogs.com/shanlu0000/p/12359814.html