C language: array definition method

1. Introduction to Arrays

<1> Preface

Let's first think about a question. If we want to define two variables and find the average of these two numbers, how should we find it?

For example: int a = 10, b = 20

int average = (a + b) / 2;

I believe that everyone should be able to find out the above formula soon.

If we want to define 5 variables and find their average value?

Are we going to write like this?

Int a = 1,b = 2,c = 3,d = 5,e = 5;

I believe that if you write it this way, everyone should be able to ask for it. However, at this time, everyone should feel that it is more troublesome. We have defined too many variables. If we ask for the average of 100 variables, then don't we have to define 100 variables. In this way, if I want to be an impatient classmate, I must have quit long ago! Therefore, our clever programmers came up with a concept called an array. 

<2> The concept of array

Array: We call a collection of variables of the same data type an array.

<3> Definition method

Data type Variable name [Number of array elements]

For example: int a[5];//We have defined 5 elements of type int.

<4> Sort in memory

  int a[5];

From the figure above, we can see that:

<1>There are 5 elements in the array, a[0],[1],a[2],a[3],a[4]

<2> The first subscript of the array is 0, and the last subscript is the number of array elements -1

<3>The size of each member in the array: The size of each member in the array group depends on the data type of the array element. At this time, the size of the array member: 4byte (one int type size)

<4>The size of the entire array = the size of an array member * the number of array elements

That is: 4 * 5 = 20;

Or sizeof(array name), the size of the array can be obtained

Note: The array name of the array indicates the first address of the first element of the array.

Take int a[5] as an example, the first element of the array is a[0], its address is &a[0], so a actually marks &a[0].

Thinking: How do we understand a[0], a[1], a[2], a[3]?

a<===>&a[0]

a[0] =====> indicates that the array name a has no offset, and then goes to the data in the corresponding address.

a[1]======> means that a is offset by an address, the size of the data type of an array element, and then the data in the address is taken

a[2]======> means that a is offset by an address, the size of the data type of 2 array elements, and then the data in the address is taken

Example code:

operation result:

Friends who are interested in the embedded Internet of Things can learn more about relevant information. (look over)

Guess you like

Origin blog.csdn.net/m0_70888041/article/details/130748186