[C language exploration tour] Part 2 Lesson 3: array, tour Part 2

Source: Internet
Author: User

[C language exploration tour] Part 2 Lesson 3: array, tour Part 2



Introduction


1. Course outline

2. Part 2 Lesson 3:Array

3. Part 2 Lesson 4 notice: String


Course outline


Our courses are divided into four parts. Each part has exercise questions after completion and answers will be published. Three games will also be written in C language.


Basic knowledge of C Programming


  • What is programming?

  • To do their best, you must first sharpen your tools.

  • Your first program

  • World of Variables

  • Computing

  • Conditional expressions

  • Loop statement

  • Practice: The first C games

  • Function

  • Exercise questions

  • Exercise: Perfect the first C games


C Advanced Technology


  • Modular programming

  • Attack pointer, C trump card

  • Array

  • String

  • Preprocessing

  • Create your own variable type

  • File read/write

  • Dynamic Allocation

  • Practice: "hanging villain" games

  • Secure text input

  • Exercise questions

  • Exercise: Explain the pointer in your own language


Develop 2D games with C language-based SDL Library


  • Install SDL

  • Create a window and canvas

  • Show images

  • Event Processing

  • Practice: "Super Mary pushes boxes" games

  • Time usage

  • Use SDL_ttf to edit text

  • Use FMOD to control sound

  • Practice: Visual Sound line

  • Exercise questions


Data Structure


  • Linked List

  • Heap, stack, and queue

  • Hash table

  • Exercise questions



Part 2 Lesson 3: Array


We ended the difficult journey of "pointer" in the previous lesson (in fact, we didn't talk much about it in the previous lesson). In this lesson, we will study the C language of "array. We will continue "all the way to the North" and "Point" where to fight.

Why do we say this? Because we need to involve pointer knowledge in this lesson, as we mentioned in the previous lesson, pointer usage almost runs through the C language, in addition, we will go deep into pointer learning. Otherwise, how can it be called the essence of C language? So "pointer, see you every day", do you think the pointer will be so "let go" you, huh, huh...

Do you want to escape now? That's not a success.


Many people who learn C language think that pointers and arrays seem a little similar and different. A bit confusing feeling, "deep feelings, rain and rain", Tangle is not clear, difficult to share.

So Let's explain this lesson: What are the relationships and differences between pointers and arrays? After learning this lesson, I believe there will be a bit of feeling that the cloud will see the fog. "Green grass, white fog," reminds me of the lyrics of the singer Li Jian singing "on the water" in the third season of "I am a singer.

You're naughty again...


Now, let's get down to the truth. In this lesson, we will learn how to create the "array" data type (or data structure ). Arrays are also very important in the C language, so you can't go over the pointer, so it's not difficult.


We will first explain the mechanism of the array in the memory (with a diagram), and the explanation of the memory is always very important. C language can be well learned only by understanding the memory mechanism. Therefore, it is recommended that you take some time to learn the third edition of assembly language compiled by Mr. Wang Shuang. It is very helpful to understand the C language and computer principles. The assembly language may not have to be learned very deeply. It is good to get started.


A programmer can well understand the mechanism behind his program and is essential for writing stable and robust programs.



Array in memory


Array is a set of variables of the same type with consecutive addresses in the memory.


Well, I know the definition "it's too difficult to study, and it's even worse ".


Simply put, an array is a "huge variable" (Why does it sound so awkward? Fortunately, I added a "variable ...), you can store a series of variables of the same type (long, double, int, char, etc ).

The number of variables (which can be called array elements or members) in the array is fixed (of course, a dynamic array can also be constructed.) It can contain 2, 3, and 10, you can store 25, 2500, or more variables.


An array composed of four elements is displayed. The address of the first element is 1600:




When you want to create an array containing four elements, you must first send a request to the "Big Manager" of the Operating System: "Can I allocate an address to my memory, to store these four elements ". Generally, the operating system starts to respond with the sound of the voice, and the stream is on, so you can allocate the address you want. However, for arrays, the storage addresses of these four elements are continuous and there is no interval between them, which is also a feature of arrays. Each element is "intimate ". As shown in, the addresses of the four elements are: 1600,1601, 1602,1603.


Each block of an address stores a number of the same type (after all, all data is a number for a computer ). If the array is of the int type, an int type number is stored in the address block of each array element. We cannot store both the int type and the double type in an array.


Summary: For arrays:

  1. When an array is created, it occupies a contiguous block of space in the memory address, and the elements of the array are one by one.

  2. All elements (members) of an array must be of the same type. For example, an int-type array can only store int-type variables, but not other variables.


Define an array

To learn how to define an array, we first define an array containing four int data types:

Int array [4];


You will say: It's so simple ...... Yes, it is so simple. You only need to write the number of elements you need in brackets, and an array is created. In general, there is no limit on the number of array members. Of course, this depends on your memory size.


Next, how do we access every array member?

It is also very simple. array [member number]


Note: The member number ranges from 0, 1, 2, until the number of elements in the array is reduced by one. Do you remember saying that the computer number starts from 0, because the computer uses binary data.

So the first element of the array is array [0], and so on. Therefore, the preceding array contains four members. Its member numbers are 0, 1, and 2, but not 4.


If I want to assign the Member values in the array to the same as in, I can do this:

Int array [4];

Array [0] = 10;

Array [1] = 23;

Array [2] = 505;

Array [3] = 8;


You will say: I don't see any relationship between arrays and pointers.

In fact, if you only write an array, It is a pointer that points to the first address of the array's first element.


For example:

Int array [4];

Printf ("% d", array );


Result output

1600


Of course, here 1600 is taken care of in the figure above. In fact, you will get other address values.


If you access the table with a subscript, you will get the member corresponding to the next tag of the array:

Printf ("% d", array [0]);


Result output

10


Similar to other subscripts. Because we know that the array name is used separately to represent a pointer, we can also obtain the value of the first element of the array as follows:

Printf ("% d", * array );


Result output

10


Similarly, we can obtain the value of the second element of the array, through the following:

* (Array + 1)


Therefore, the results of these two expressions are the same, both of which are 23:

Array [1]

* (Array + 1)


Array with variable number of elements

The C language has many versions (almost all programming languages). In the latest C99 version, an array of variable sizes can be created, that is, the number of elements is a variable:

Int variable = 5;

Int array [variable];


However, this new feature is not recognized by all C compilers, so some compilers may encounter errors in the second line. The reference and C language standards in our courses are C89, so we cannot have a variable-size array in our courses.


We need to reach an agreement:

The number of elements in the array (the number in brackets) must be a constant, not a variable, or even a const variable. The array must have a fixed size.


You will ask: Isn't it possible to create an array with a variable number of elements?

The answer is: you can create an array with an uncertain number of elements at the beginning, even in C89. However, to achieve this goal, we need to use another technology:Dynamic Allocation. Later courses will be discussed.


Traverse an array

If we want to display the values of each member in the array.

Of course I can use printf to output data one by one, but there may be too many code. It is better to use a loop for display, such as the common for loop:

Int main (int argc, char * argv [])

{

Int array [4], I = 0;

Array [0] = 10;

Array [1] = 23;

Array [2] = 505;

Array [3] = 8;

For (I = 0; I <4; I ++)

{

Printf ("% d \ n", array [I]);

}

Return 0;

}


Program output:

10

23

505

8


Our for loop uses a variable called I to traverse our array. In fact, I is a very common variable name. Most programmers like to use it to traverse the array, because I is the first letter of index (subscript.

We should have discovered that when defining an array, we cannot put a variable in the brackets [] (the number of members of the array needs to be determined ), however, variables can be placed in brackets during array traversal.


Note: do not try to access array [4] Because you will get any data or get an error because this address has produced an "array out of bounds ", the operating system will abort your program because your program attempts to access an address that has no access permission.


Initialize an array

Now that we know how to traverse an array, we should be able to easily Initialize an array: We can use the for loop to initialize all the members of the array to 0.


Int main (int argc, char * argv [])

{

Int array [4], I = 0;

// Array Initialization

For (I = 0; I <4; I ++)

{

Array [I] = 0;

}

// Print the members of the array to determine the value.

For (I = 0; I <4; I ++)

{

Printf ("% d \ n", array [I]);

}

Return 0;

}


Output:

0

0

0

0


Another method for initializing Arrays

After reading the above initialization method, I think it is not enough. We need to know that there is another initialization method, which is to write like this:

Array name [4] = {value 1, value 2, value 3, value 4 };


Simply put, the values of each member are written in braces and separated by commas, as follows:


Int main (int argc, char * argv [])

{

Int array [4] = {0, 0, 0}, I = 0;

For (I = 0; I <4; I ++)

{

Printf ("% d \ n", array [I]);

}

Return 0;

}


The output is also:

0

0

0

0


In fact, it can be easier. It is to write the initial values of the first few members, and the values of the subsequent members. If you do not give the initial values, the values will be automatically initialized to 0:


Int array [4] = {10, 23}; // initialization value: 10, 23, 0, 0


The value obtained by the first member is 10, the second is 23, and the third and fourth are initialized to 0.


Then, how can we Initialize all the members of the array to 0 simply by writing:


Int array [4] = {0 };


In this way, all members are initialized to 0.


Pass the array to the Function

When writing a program, we may need to display the values of all the members of an array. Why not write this function as a function?

With this applet, we can also learn how to pass an array as a parameter to the function.


We need to pass two parameters to the function: array (actually the address of the array) and array size.

As we have said before, if the array name is used directly, it is actually a pointer pointing to the first address of the array's first element! So we can write our program like this:


Void display (int * array, int arraySize );


Int main (int argc, char * argv [])

{

Int array [4] = {10, 15, 3 };


// Display the array content

Dispaly (array, 4 );


Return 0;

}


Void display (int * array, int arraySize)

{

Int I;


For (I = 0; I <arraySize; I ++)

{

Printf ("% d \ n", array [I]);

}

}


Program output:

10

15

3

0


The above function display seems to be no different from the function we used in the pointer class, the first parameter of this function is a pointer to the int type (our array name is array ). The second parameter is the size of the array (number of members) to know when our for loop will be aborted.


There is also another way to indicate that a function accepts an array as a parameter, so write:

Void display (int array [], int arraySize );


This time I used brackets to indicate that the parameter accepts an array, but the first element of the array is actually passed to the function, the entire array is not passed (because copying the entire array is costly ). The advantage of this writing is that the reader will not mistakenly think that the accepted parameter is a common pointer. Of course, this time, the array size does not need to be written in brackets.

I use both methods when writing a program, but it is generally used in brackets to avoid confusion.


Some small exercises

I learned today's lesson and want everyone to implement some functions related to arrays.

Here we only provide a description of exercise questions. You need to think about how to implement these functions. Then we can discuss it in our programmer Alliance's QQ group and group.


Exercise 1

Returns the average value of an array. Function template:

Double arrayAverage (int array [], int arraySize );


Exercise 2

Write a function to copy an array. This function has three parameters. The first and second parameters are the array name, and the third parameter is the array size. Copy the content of the first parameter (array) to the second parameter (array. Function template:

Void copyArray (int originalArray [], int copyArray [], int arraySize );


Exercise 3

Write a function with three parameters. The first parameter is an array, the second parameter is the array size, and the third parameter is the maximum value. If the value of a Member in this array is greater than the maximum value, the value of this Member is changed to 0. Function template:

Void arrayMax (int array [], int arraySize, int valueMax );


Exercise 4

This exercise is the most difficult. Write a function to sort the array by the Member values from small to large. For example, the array is originally [15, 81, 22, 13] And then changed to [13, 15, 22, 22, 81]. Function template:

Void orderArray (int array [], int arraySize );


Come on. Welcome to the discussion.


Summary

  1. An array is a collection of data of the same type. In the memory, each member of the array is adjacent

  2. In general, the size of the array (number of members) must be fixed and cannot be replaced by a variable (dimension)

  3. Each member of an array of the int type must be of the int type.

  4. The subscript of each member in the array starts from 0, such as array [0], array [1], array [2 ].



Part 2 Lesson 4:


Today's class is here to cheer up.

Next time we will take the second part and the fourth lesson:String



Programmer Alliance Community

At present, there is a group and a QQ group (all of which have already broken through a hundred people). Anyone interested in programming can add them. You can exchange, learn, interact, and share the source code of the program.


Group (programmer Alliance). If you want to add a group, please send a private message to me. (if the number of groups exceeds 100, you cannot scan the QR code to join the group. You can only send a private message to me. Thank you)


QQ group (programmer Alliance), with the group number 413981577

There are N multi-programming PDF files in the QQ group sharing. Scan the following QR code and add the QQ group:


We have also created a public Baidu cloud disk with 2 TB capacity for you to upload excellent programming resources, which will be sent after the link is added to the group.


My number can be seen at the end of the article, QQ and mailbox are also at the end.


We have also created a micro-community for the programmer alliance to facilitate questions and interactions. Take a look.

The micro-community address and QR Code are as follows:

Http://m.wsq.qq.com/264152148

Thank you!



Programmer Alliance public account* If you think this article is good, click "share to friends" or "send to friends" in the upper-right corner of the screen"

* New friends should follow the "Programmer alliance" Search Public AccountProgrammerleleague

Small No.: frogoscar

Xiaobian QQ: 379641629

Alimail: enmingx@gmail.com

Programmer Alliance QQ group: 413981577


PS: A friend reported that reading articles on the mobile phone is too tired. In fact, they can be viewed on a browser webpage.

Method 1. click the "·" button in the upper-right corner of the screen, select "Copy link", paste the link to your browser, or send it to yourself by email, you can open it in your computer's browser.



Method 2. toutiao.comWww.toutiao.com, Search my self-Media "Programmer alliance", which has an article, you can also directly into this link: http://www.toutiao.com/m3750422747/


Method 3. My 51CTO blog and CSDN blog Link (all articles will be posted on it)
Http://4526621.blog.51cto.com/

Http://blog.csdn.net/frogoscar



How do new friends view all articles:

Click "view public account" and then "view historical messages"





"Programmer Alliance"The public account is designed for programmers,App designer,Everyone who loves programming and sharing pushes a wide range of programming-related knowledge, excellent software recommendations, and industry trends. SearchProgrammerleleagueADD Attention ~


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.