How many ways do you know how to assign an initial value to a two-dimensional array?

There are several ways to assign an initial value to a two-dimensional array

method one

  • Assign an initial value to a two-dimensional array by line:
int arr[3][4]={
    
    {
    
    1,2,3,4},{
    
    5,6,7,8},{
    
    9,10,11,12}};

This assignment method is simple and intuitive, giving the value of the first curly brace to the first line, and so on.

Question: arr[2][0]=?
Answer: 9

Method Two

  • Assign values ​​to elements in array order:
int arr[3][4]={
    
    1,2,3,4,5,6,7,8,9,10,11,12};

Disadvantage: If there is a lot of data, it is easy to be missed and inconvenient to check.

Question: arr[1][2]=?
Answer: 7

Method three

  • assign values ​​to some elements
int arr[3][4]={
    
    {
    
    1},{
    
    5},{
    
    9}};

Elements that are not assigned an initial value default to 0.
Advantages: It is suitable for situations where there is a lot of data and many zeros. It is not necessary to mark each zero, and only a small amount of data needs to be input.

Question: arr[2][3]=?
Answer: 0

Method 4

  • When assigning initial values ​​to all elements, the length of the first dimension can be omitted. The system will judge the length of the second dimension according to the total number of data, but the length of the second dimension cannot be omitted.
int arr[][4]={
    
    1,2,3,4,5,6,7,8,9,10,11,12}

The system will allocate storage space according to the total number of data, a total of 12 data, each row 4 columns, of course, can be determined to be 3 rows.

Question: arr[2][2]=?
Answer: 11

Method five

  • When assigning initial values ​​to some elements, the one-dimensional length can also be omitted, but the initial values ​​need to be assigned in separate lines.
int arr[][4]={
    
    {
    
    1,2,3,4},{
    
    },{
    
    9,10,11,12}};

Question: arr[1][2]=?
Answer: 0

Guess you like

Origin blog.csdn.net/zhangxia_/article/details/121198098