当前位置:网站首页>Introduction of several ways to initialize two-dimensional arrays in C language (private way to initialize large arrays)

Introduction of several ways to initialize two-dimensional arrays in C language (private way to initialize large arrays)

2022-08-11 05:45:00 FussyCat

1、直接赋值

Suitable for arrays with fewer elements,The value of each element can be different.

int arr1[2][3] = {
     {
    5, 2, 4}, {
    10, 2, 1} };
int arr1[2][3] = {
    0}; /* 所有元素都初始化为0 */
int arr1[2][3] = {
    1}; /* 只有arr1[0][0]为1,All other elements are initialized to 0 */

2、The loop assigns values ​​to each element

Assign a value to each element of the array,The value of each element can be different.就是效率比较低.

int arr2[2][3];
int i, j;
for (i = 0; i < 2; i++) {
    
    for (j = 0; j < 3; j++) {
    
        arr2[i][j] = 2; /* In this example, both are assigned the same value for simplicity */
    }
}

3、借用memset/memset_s初始化为0或-1

注意:memset/memset_sVariables can only be initialized as 0或-1,Other values ​​do not hold. 参考百度百科 The first of the common mistakes.
A lot of people don't notice this,容易犯错.

int arr3[10][10];
memset(arr3, 0, sizeof(arr3); /* 正常,arr3中的每个元素都为0 */
memset(arr3, -1, sizeof(arr3); /* 正常,arr3中的每个元素都为-1 */
memset(arr3, 2, sizeof(arr3); /* 异常,arr3Each element in is an outlier33686018 */

在这里插入图片描述

4、All elements of the array are initialized to the same value(It is convenient for initialization of large arrays)

as long as the values ​​are the same,Especially when there are many array elements,推荐用此方法:
{ [0 … LENA-1][0 … LENB-1] = num };
This initialization method is relatively rare,But especially convenient,所以共享给大家.

#define ARR_LEN 100
int arr4[ARR_LEN][ARR_LEN] = {
     [0 ... (ARR_LEN-1)][0 ... (ARR_LEN-1)] = 10 }; /* 100*100个元素都初始化为10 */

在这里插入图片描述

原网站

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