当前位置:网站首页>How many ways can you assign initial values to a two-dimensional array?

How many ways can you assign initial values to a two-dimensional array?

2022-07-25 14:45:00 Hua Weiyun

How many ways can you assign initial values to a two-dimensional array
@TOC

Method 1

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

This assignment method is simple and intuitive , Give the value of the first curly bracket to the first line , One analogy .

ask :arr[2][0]=?
answer :9

Method 2

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

shortcoming : If there's more data , Easy to miss , Inconvenient to check .

ask :arr[1][2]=?
answer :7

Method 3

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

The element without initial value is... By default 0.
advantage : It is applicable to the situation with more data and more zeros , There is no need to mark every zero , Just input a small amount of data .

ask :arr[2][3]=?
answer :0

Method four

  • 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 , altogether 12 Data , Each row 4 Column , Of course, it can be determined as 3 That's ok .

ask :arr[2][2]=?
answer :11

Method five

  • When assigning initial values to some elements , The length of one dimension can also be omitted , But the initial value needs to be assigned to the branch .
int arr[][4]={{1,2,3,4},{},{9,10,11,12}};

ask :arr[1][2]=?
answer :0

原网站

版权声明
本文为[Hua Weiyun]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/206/202207251437473419.html