[C language array] Creation, initialization, and use

Article directory

  • Preface
  • 1. ?-dimensional array
    • 1.1 Array creation
    • 1.2 Initialization of array
    • 1.3 Types of arrays
  • 2. How to use ?dimensional array?
    • 2.1 Array subscript
    • 2.2 Printing of array elements
    • 2.3 Loss of array?
    • 2.4 Storage of ?-dimensional arrays in memory
  • 3. sizeof calculates the number of array elements
  • 4. Creation of ?-dimensional array
    • 4.1 The concept of ?-dimensional array
    • 4.2 Creation of ?-dimensional array
    • 4.2 Initialization of ?-dimensional array
      • 4.2.1 Incomplete initialization
      • 4.2.2 Full initialization
      • 4.2.3 Initialize according to?
      • 4.2.3 Omit ? during initialization, but columns cannot be omitted
  • 5. Use of two-dimensional arrays
    • 5.1 Subscripts of ?-dimensional arrays
    • 5.2 Input and output of ?-dimensional array
    • 5.3 Storage of ?-dimensional arrays in memory

Foreword

  1. The concept of array

An array is a collection of elements of the same type:

? The array stores one or more data, but the number of array elements cannot be 0.
? Multiple data types stored in the array are of the same type.

Arrays are divided into one-dimensional arrays and multi-dimensional arrays. Multi-dimensional arrays are generally two-dimensional arrays.

1. ?Dimensional array

1.1 Array creation

The basic syntax for creating a ?dimensional array is as follows:

1 type arr_name[constant value];

The values stored in the array are called array elements. The array elements and array elements types can be specified when the array is created.

? type specifies the type of data stored in the array, which can be: char, short, int, float Wait, you can also define the type
? arr_name refers to the name of the array name. This name should be meaningful according to the actual situation.
The constant values in [] are used to specify the size of the array. The size of this array is specified based on actual requirements.

For example: We now want to store the 20% math score of a certain class, then we can create an array, as follows:

1 int math[20];

Of course, we can also create arrays of other types and as needed:

1 char ch[6];
2 double score[8];

1.2 Initialization of array

Sometimes, an array needs to be given some initial values when it is created, which is called initialization.
So how to initialize the array? Arrays are generally initialized using braces and the data is placed in braces.
For example, you will understand:

1 //Fully initialized
2 int arr[5] = {<!-- -->1,2,3,4,5};
3
4 //Incomplete initialization
5 int arr2[6] = {<!-- -->1};//The ?th element is initialized to 1, and the remaining elements are initialized to 0 by default
7
8 //Wrong initialization - too many initialization items
9 int arr3[3] = {<!-- -->1, 2, 3, 4};//will cause the array to go out of bounds and cause bugs

1.3 Type of array

Arrays also have types. Arrays are considered a defined type. What remains after removing the array name is the type of the array.

1 int arr1[10];
2 int arr2[12];
3 char ch[5];

The type of the arr1 array is int [10]
The type of the arr2 array is int[12]
The type of ch array is char[5]

2. How to use ?dimensional array?

We have learned the basic syntax of 1-dimensional arrays. 1-dimensional arrays can store data. The purpose of storing data is to operate on data. So how do we use 1-dimensional arrays?

2.1 Array subscript

C language stipulates that arrays have subscripts, and the subscripts start from 0. Assume that the array has n elements, and the last ones are The subscript of the element is n-1, and the subscript is equivalent to the number of the array element, as follows:

In the C language, array access provides two operators []. This operator is called: Subindex operator.
With the subscript access operator, we can easily access the elements of the array. For example, if we access the element with subscript 7, we can use arr[7] , if you want to access the element whose subscript is 3, you can use? arr[3], the following code:

#include <stdio.h>
int main()
{<!-- -->
 int arr[10] = {<!-- -->1,2,3,4,5,6,7,8,9,10};
printf("%d\
", arr[7]);//Print 8
 printf("%d\
", arr[3]);//Print 4
 return 0;
}

Output:

2.2 Printing of array elements

Next, what should you do if you want to access the contents of the entire array? Just use the for loop to generate the subscripts of 0~9, and then use the subscripts to access the elements in the array. The specific code is as follows:

#include <stdio.h>
int main()
{<!-- -->
 int arr[10] = {<!-- -->1,2,3,4,5,6,7,8,9,10};
 int i = 0;
 for(i=0; i<10; i + + )
 {<!-- -->
 printf("%d ", arr[i]);
 }
 return 0;
}

2.3 Array input?

We understand the access of the array. Of course, according to our needs, we can’t just put a few values in the curly braces, so we can enter the data we want into the array. So how do we achieve it? as follows:

#include <stdio.h>
int main()
{<!-- -->
    int arr[10] = {<!-- --> 1,2,3,4,5,6,7,8,9,10};
    int i = 0;
    printf("Please enter\
");
    for (i = 0; i < 10; i + + )
    {<!-- -->
        scanf("%d", & amp;arr[i]);
    }
    printf("output\
");
    for (i = 0; i < 10; i + + )
    {<!-- -->
        printf("%d ", arr[i]);
    }
    return 0;
}

Input and output:
Please add image description

2.4 Storage of ?-dimensional arrays in memory

With the previous knowledge, there are basically no obstacles for us to actually use arrays. If we want to understand arrays in depth, it is best to understand how arrays are stored in memory.

#include <stdio.h>
int main()
{<!-- -->
 int arr[10] = {<!-- -->1,2,3,4,5,6,7,8,9,10};
 int i = 0;
 for(i=0; i<10; i + + )
 {<!-- -->
 printf(" & amp;arr[%d] = %p\
", i, & amp;arr[i]);
 //Use & amp; to get the address symbol and print the storage address of the array
 }
 return 0;
}

Please add image description

From the output results, we analyze that as the subscript increases, the address of the array changes from ? to ?, and we find that every two adjacent
The difference between the elements is 4 (because each integer is 4 bytes). So we conclude that arrays are stored continuously in memory. I will continue to explain pointer access to arrays to avoid making the article too long.

3. sizeof calculates the number of array elements

When traversing an array, we often want to know the number of elements in the array. Is there a way in C to use the program to calculate the number of elements in the array?
The answer is yes, you can use ?sizeof.
sizeof is a keyword in C language that can calculate the size of a type or variable. In fact, sizeof can also calculate the size of an array.
?like:

#include <stido.h>
int main()
{<!-- -->
 int arr[10] = {<!-- -->0};
 printf("%d\
", sizeof(arr));
 return 0;
}

The output result is 40, which calculates the total memory space occupied by the array, and the unit is bytes.

We know that all elements in the array are of the same type, so as long as we calculate the number of bytes occupied by each element, the number of elements in the array can be calculated. At this point we just select the first element and calculate it.

#include <stido.h>
int main()
{<!-- -->
 int arr[10] = {<!-- -->0};
 printf("%d\
", sizeof(arr[0]));//Calculate the size of each element, the unit is bytes
 return 0;
}

Calculate the length of each element, the unit is bytes

Next, you can calculate the number of elements in the array:

#include <stido.h>
int main()
{<!-- -->
 int arr[10] = {<!-- -->0};
 int sz = sizeof(arr)/sizeof(arr[0]);//40/4=10
 printf("%d\
", sz);
 return 0;
}

The result of this is: 10, indicating that the array has 10 elements.
In the future, where the number of array elements is required in the code, it will be fixed and hard-coded. Using the above calculation, no matter how the array changes, the calculated value will also change.

4. Creation of ?dimensional array

4.1 The concept of ?dimensional array

The array we studied earlier is called a one-dimensional array. The elements of the array are all built-in types. If we use a one-dimensional array as an element of the array, it is a two-dimensional array. Two-dimensional array An array whose elements are arrays is called a three-dimensional array. Arrays above two-dimensional arrays are collectively called multi-dimensional arrays.

4.2 Creation of ?-dimensional array

So how do we define a ?dimensional array? The syntax is as follows:

type arr_name[constant value 1][constant value 2];

For example:
int arr[3][5];
double data[2][8];

Explanation: The information appearing in the above code
? 3 tables? Arrays have 3 ?
? 5 table? each has 5 elements
? int table? Each element of the array is an integer type
? arr is the array name, you can specify the name according to the needs of
dataThe meaning of array is basically the same?

4.2 Initialization of ?dimensional array

When creating a variable or array, giving some initial values is called initialization.
So how to initialize the dimensional array? Like a two-dimensional array, it is also initialized using square brackets.

4.2.1 Incomplete initialization

int arr1[3][5] = {<!-- -->1,2};
int arr2[3][5] = {<!-- -->0};

Except for 1 and 2 stored in it, the others are initialized to 0 by default.

4.2.2 Full initialization

int arr3[3][5] = {<!-- -->1,2,3,4,5, 2,3,4,5,6, 3,4,5,6,7} ;

arr3 array:

4.2.3 Initialize according to ?

1 int arr4[3][5] = {<!-- -->{<!-- -->1,2},{<!-- -->3,4},{<! -- -->5,6}};

4.2.3 Omit ? during initialization, but columns cannot be omitted

1 int arr5[][5] = {<!-- -->1,2,3};
2 int arr6[][5] = {<!-- -->1,2,3,4,5,6,7};
3 int arr7[][5] = {<!-- -->{<!-- -->1,2}, {<!-- -->3,4}, {<!-- -- >5,6}};

5. Use of two-dimensional array

5.1 ?Subscript of dimensional array

Once we have mastered the creation and initialization of two-dimensional arrays, how do we use two-dimensional arrays?

In fact, access to two-dimensional arrays is also performed in the form of subscripts. A two-dimensional array has rows and columns. As long as the rows and columns are determined, an element in the array can be uniquely determined.

C language stipulates that the rows of a two-dimensional array start from 0, and the columns also start from 0, as shown below:

1 int arr[3][5] = {<!-- -->1,2,3,4,5, 2,3,4,5,6, 3,4,5,6,7 };

The green number on the far right in the picture represents the system number, and the blue number on the far right represents the column number. They all start from 0. For example, we say: No. 2
?, column 4, you can quickly locate 7.

include <stdio.h>
int main()
{<!-- -->
 int arr[3][5] = {<!-- -->1,2,3,4,5, 2,3,4,5,6, 3,4,5,6,7};
 printf("%d\
", arr[2][4]);
 return 0;
 }

5.2 Input and output of dimensional array

We know how to access a single element of a ?-dimensional array, but how to access the entire ?-dimensional array?
In fact, as long as we can produce all the numbers and column numbers according to certain rules; taking the arr array in the above code as an example, the selection range of ? is 0~2, and the value range of the column is 0~4 , so we can achieve all subscripts with the help of loops.

#include <stdio.h>
int main()
{<!-- -->
 int arr[3][5] = {<!-- -->1,2,3,4,5, 2,3,4,5,6, 3,4,5,6,7};
 int i = 0;//Traverse?
 \t//lose?
 for(i=0; i<3; i + + ) //Production number
 {<!-- -->
 int j = 0;
 for(j=0; j<5; j + + ) //Production column number
 {<!-- -->
 scanf("%d", & amp;arr[i][j]); //Input data
 }
}
 //Output
 for(i=0; i<3; i + + ) //Production number
 {<!-- -->
 int j = 0;
 for(j=0; j<5; j + + ) //Production column number
 {<!-- -->
 printf("%d ", arr[i][j]); //Output data
 }
 printf("\
");
}
return 0;
}

Please add image description

5.3 Storage of ?dimensional arrays in memory

Like a one-dimensional array, if we want to study how a two-dimensional array is stored in memory, we can also print out the addresses of all elements of the array. code show as below:

#include <stdio.h>
int main()
{<!-- -->
 int arr[3][5] = {<!-- --> 0 };
 int i = 0;
 int j = 0;
 for (i = 0; i < 3; i + + )
 {<!-- -->
 for (j = 0; j < 5; j + + )
 {<!-- -->
 printf(" & amp;arr[%d][%d] = %p\
", i, j, & amp;arr[i][j]);
 }
 }
 return 0;
}

Please add image description
Judging from the output results, each element in each row is adjacent, the address difference is 4 bytes, and the two elements at the cross-row position (such as: arr[0][4] and arr[1] [0]) are also 4 bytes apart, so each element in the two-dimensional array is stored continuously.

Each element of the ?-dimensional array is stored continuously in memory.