Current location - Plastic Surgery and Aesthetics Network - Plastic surgery and beauty - What is the concept of array?
What is the concept of array?
An array is a collection of several variables of the same type, which can be referenced by the same name. An array consists of consecutive memory cells, with the lowest address corresponding to the first element and the highest address corresponding to the last element. Arrays can be one-dimensional or multi-dimensional.

5. 1 one-dimensional array

A general description of a one-dimensional array is as follows:

Type specifier var _ name [size];

In C language, arrays must be clearly described so that the compiler can allocate memory space for them. In the above formula, the type specifier indicates the type of the array, that is, the number of each element in the array, and the total number of bytes in a one-dimensional array can be calculated as follows:

Sizeof (type) * array length = total bytes

[Example 5- 1] Loads the numbers 0 to 9 into an integer array.

Master ()

{

int x[ 10]; /* Define an array containing 1 0 integers, and refer to it as x [0], x [1]...x [9] */

int t;

for(t = 0; t & lt 10; ++ t)x[t]= t;

}

C language does not check the array boundary, so both ends of the array may cross the line, destroying the array of other variables and even the program code. It is the programmer's responsibility to check the boundaries of the array when necessary. For example, when using gets () to receive character input, you must ensure that the length of the character array is enough to accommodate the longest string.

A one-dimensional array is essentially a table composed of similar data, for example, for the following array A:

char a[7]

Figure 5- 1 illustrates the situation of array A in memory, assuming the starting address is 1000.

5. 1. 1 Pass a one-dimensional array to the function.

When passing a one-dimensional array to a function, you can call the function directly, taking the array name as a parameter, without any subscripts. In this way, the address of the first element of the array will be passed to the function. C language does not pass the whole array as a parameter, but uses a pointer instead. For example, the following program passes the address of the first element of array I to the function func 1 ().

Master ()

{

int I[ 10];

func 1(I); /* Function call, parameter is array name */

. . .

}

If a function wants to receive the passing of a one-dimensional array, it can use one of the following two methods to explain the formal parameters; 1) bounded array; 2) unbounded array. For example, the function func 1 () can receive the array i as follows:

Func 1 (string)

char str[ 10]; /* Bounded array, the subscript of the array can only be less than or equal to the size of the transitive array. * /

{

.

. .

}

It can also be interpreted as:

Func 1 (string)

char str[]; /* unbounded array */

{

.

. .

}

The effect of these two methods is equivalent, both of which tell the compiler to establish a character pointer. The first description uses standard array description; The latter description uses an improved array description, which only shows that the function will receive an integer array with a certain length. Come to think of it, as far as functions are concerned, it doesn't matter how long the array is, because C language doesn't check the boundaries of the array. In fact, as far as the compiler is concerned, the following instructions are also feasible.

func 1(str);

int str[32];

{

. . .

}

Because the compiler only generates code to let the function func 1 () receive a pointer, it doesn't really generate an array with 3 2 elements.

One-dimensional array for 5. 1.2 strings.

Obviously, the most common use of one-dimensional arrays is as strings. In C language, a string is defined as an array of characters ending in a null character. Empty characters are identified by' \ 0' and are usually not displayed. Therefore, when describing a character array, you must have one more character than the longest string it wants to store. For example, if you want to define an array s to store a string of length 1 0, you can write it as follows:

char s[ 1 1];

This leaves room for empty characters at the end of the string.

Although C language does not define strings as data types, it allows string constants to be used. A string constant is a list of characters enclosed in double quotes. For example, the following two phrases are both string constants:

"Hello"

"This is a test"

There is no need to add null characters at the end of the string, and the C compiler will do this automatically.

C language supports multi-string operation functions, the most commonly used are:

Name function

Strcpy(s 1 s2) copies s2 to s 1.

Strcat(s 1 s2) connects s2 to the end of s 1.

Strlen(s 1) returns the length of s 1

Strcmp(s 1, s2) If s 1 equals s2, the return value is 0.

If s 1

If s 1 > S2, the return value is greater than 0.

Example 5-2 illustrates the usage of these functions.

[Example 5-2]

# include & ltstdio.h & gt

Master ()

{

char s 1[80],S2[80]; /* Define an array of characters */

gets(s 1); /* Enter the string */

Obtaining (S2);

printf ("lengthsf: %d %d\n ",strlen(s 1),strlen(S2));

If (! strcmp(s 1,s2))

Printf ("string equality \ n");

strcat(s 1,S2);

printf ("%s\n ",s 1);

}

Remember, when two strings are equal, the function strcmp () will return Fa l s e, so when testing the equivalence of strings, like the previous example, logical operators must be used! Reverse the test conditions.

When the program runs and accepts two strings "hello" and "hello" as input, its output is:

hello

hello

Length: 5 5

The strings are equal.

hellohello

5.2 two-dimensional array

5.2. General form of1two-dimensional array

C language allows the use of multidimensional arrays, and the simplest multidimensional array is a two-dimensional array. In fact, a two-dimensional array is an array composed of one-dimensional arrays. To interpret d as a two-dimensional integer array of size (10,20), it can be written as:

int d[ 10][20]

Please pay attention to the above statement. Unlike most other computer languages, C does not use commas to distinguish subscripts, but uses square brackets to enclose the subscripts of each dimension, and the two-dimensional subscripts of the array are calculated from 0.

Similarly, the element with subscript (3,5) to be accessed in array D can be written as:

d[ 3 ][ 5 ]

In Example 5-3, integers 1 to 12 are loaded into a two-dimensional array.

[Example 5-3]

Master ()

{

int t,I,num[3][4]

for(t = 0; t & lt3; ++t)

for(I = 0; I<4; ++i)

num[t][I]=(t * 4)+I+ 1;

}

In this example, the values of num[0][0] are 1, num[0][2] is 3, and num[2][3] is12. You can think of this array as the following table:

0 1 2 3

0 1 2 3 4

1 5 6 7 8

2 9 10 1 1 12

Two-dimensional arrays are stored in the form of row and column matrices. The first subscript represents rows and the second subscript represents columns, which means that when accessing array elements in the actual storage order in memory, the subscripts on the right change faster than those on the left. Figure 5-2 shows a two-dimensional array in memory. In fact, the first subscript can be regarded as a pointer to a line.

Remember, once the array is proved, all the array elements will be allocated corresponding storage space. For a two-dimensional array, you can use the following formula to calculate the number of memory bytes required:

Number of rows × number of columns × number of type bytes = total number of bytes

Therefore, assuming a two-byte integer, an integer array of size (10,5) will need: 10×5×2= 100 bytes. When a two-dimensional array is used as a parameter of a function, it actually passes a pointer to the first element (such as [0] [0]). However, this function must define at least the length of the second dimension, because if the C compiler wants to retrieve the array correctly, it needs to know the length of each row. For example, the function of receiving a two-dimensional array of size (10, 10) can be described as follows:

func 1(x)

int x[ ][ 10]

{

.

. .

}

You can also specify the length of the first dimension, but this is not necessary.

The C compiler compiles the following statements in the function:

X[2][4]

When processing, you need to know the length of two dimensions. If the president is not defined, it is impossible to know where the third line begins [Example 5-4]. A two-dimensional array is used to store the students' scores of each class taught by a teacher. Suppose the teacher has three classes, and each class has at most thirty students. Notice how each function accesses the array.

# Define Category 3

# Define Level 30

# include & ltstdio.h & gt

Master ()

{

void enter _ grades();

void disp _ grades();

int get _ grade();

Int a[ class] [level]; /* Define a two-dimensional array, and store the scores of one class in each row */

char ch

for(; ; )

Do {/* menu display */

Printf("(E) Enter grades \ n ");

printf("(R)eport grades \ n ");

printf("(Q)uit \ n ");

ch = toupper(getchar()); /* Convert keyboard input characters to uppercase */

} while(ch! = ' E ' & amp& ampch! = ' R ' & amp& ampch! = ' Q ');

Switch (channel)

Case "e":

enter _ grades();

Break;

Case "r":

Disp_grades (grade);

Break;

Case "q":

Exit (0);

}

}

}

void enter_grades(a)

Int a[][ achievement];

{

int t,I;

for(t = 0; T< class; t++)

{

printf("class #%d:\n ",t+ 1);

for(I = 0; My< grades; i++)

a[t][I]= get _ grade(I);

}

}

Int get_grades (number)

int num

{

char s[80];

Printf ("Enter the score of student # %d: \n", n um+1);

Obtain; /* Enter the score */

Return (atoi (s));

}

Void disp_grades(g) /* Displays students' grades */

Int g[][ achievement];

{

int t,I;

for(t = 0; T< class; ++t) {

printf("class # %d:\n ",t+ 1);

for(I = 0; My< grades; ++i)

Printf ("the score of student #%d is %d\n", i+1, g [t] [i]);

}

}

We simplify the actual problem to * * * there are two classes, and each class has two students. That is to say, we modify the definition of constants in the program as follows:

# Define Category 2

# Define Level 2

Run the program:

(e) Winter grade

(r) reporting level

(Q)uit: e

Category # 1:

Enter the score of student # 1: 7 8.

Enter the grade of student #2: 8 9

second kind

Enter the score of student # 1: 9 8.

Enter the score of student #2: 9 0

(e) Winter grade

(r) reporting level

(Q)uit: r

Category # 1

The score of student # 1 is 78

The score of student No.2 is 89

second kind

The score of student # 1 is 98

The score of student No.2 is 90.

(e) Winter grade

(r) reporting level

Uit: q

When we run the program, we first see a menu, select "E" to enter grades, "R" to display grades, and select "Q".

The quit atoi () function is used to convert a parameter string into an integer.

String array

String arrays are often used in programming. For example, the input processor of the database compares the command input by the user with the valid command stored in the string array to verify its validity. You can create a string array in the form of a two-dimensional character array. The left subscript determines the number of strings, and the right subscript indicates the maximum length of strings. For example, the following statement defines a string array, which can hold 3 0 strings with a maximum length of 8 0 characters:

char str _ array[30][80];

Accessing a single string is easy, just mark the left subscript. For example, the following statement calls the function gets () and takes the third string in the array str_array as a parameter.

Get (str _ array [2]);

This statement is functionally equivalent to:

Get (& ampstr _ array [2] [0]);

But the first form is more common in C language programs written by professional programmers.

To help understand the usage of string arrays, learn Example 5-5. It performs simple text editing based on an array of strings.

[Example 5-5]

# include & ltstdio.h & gt

# Define Max 100

# Define Lens 80

char text [MAX][LEN]

/* A very simple text editor */

Master ()

{

Registers int t, I, j;

for(t = 0; T & ltMAXT++) /* Enter the string line by line */

{

printf("%d:",t);

gets(text[t]);

If (! text[t][0])

Break; /* Blank line exits */

}

for(I = 0; I<t, i++) /* Output the string line by line and character by character */

{

for(j = 0; Text [I] [j]; j++)

putchar(text[I][j]);

putchar(' \ n ');

}

}

The program enters lines of text until it encounters blank lines, and then redisplays them one character at a time.

5.3 Multidimensional array

C language allows arrays to be larger than two dimensions, and the limitation of dimensions (if any) is determined by a specific compiler. The general description form of multidimensional array is:

Type descriptor name [a] [b] [c] ... [z];

Two-dimensional or multidimensional arrays are rarely used because they occupy a lot of memory. As mentioned earlier, when an array is defined, all the array elements will be assigned to the address space. For example, a four-dimensional character array with the size of (10,6,9,4) needs 10×6×9×4, that is, 2 160 bytes.

If the above array is a two-byte integer, it needs 4320 bytes, and if the array is a double word (assuming each double word is 8 bytes), it needs 34560 bytes, and the storage capacity increases exponentially with the increase of dimension.

One thing to note about multidimensional arrays is that computers spend a lot of time calculating array subscripts, which means that accessing elements in multidimensional arrays takes more time than accessing elements in one-dimensional arrays. For these and other reasons, a large number of multidimensional arrays generally use C language to dynamically allocate functions and pointers, and dynamically allocate storage space for a part of the array at a time.

When passing a multidimensional array to a function, all dimensions except the first dimension must be interpreted. For example, the array m is defined as:

int m[4][3][6][5];

Then the function that receives m should be written as:

func 1 (d)

int d[][3][6][5];

Of course, you can also add a description of the first dimension if you like.

5.4 Initialization of Array

6.5438+0 array initialization

C language allows initialization of global arrays and static local arrays during description, but it cannot initialize non-static local arrays.

Similar to other variables, the general form of array initialization is as follows:

Type specifier array _ name [size1] ... [size] = {value-list};

The table of values is a comma-separated table of constants. The types of these constants are compatible with the type descriptions. The first constant is stored in the first cell of the array, the second constant is stored in the second cell, and so on. Note that a semicolon should be added after the bracket "}".

Initialize one of the following integer arrays of 1 0 elements and load the numbers 1 to 10:

int i[ 10]={ 1,2,3,4,5,6,7,8,9, 10 };

This means that the value of i[0] is 1, and the value of i[9] is 10.

Initialization of the character array used to store the character string can take the following simplified form:

char array _ name[size]= " string ";

For example, the following code snippet initializes str to "hello".

char str[6]= " hello ";

The above code produces the same result as the following code:

char str[6]={'h ',' e ',' l ',' l ',' \ o ' };

Because all strings in the C language end with null characters, make sure that the defined array is long enough to accommodate null characters. That's why h ello is only five characters long and str is six characters long. When using string constants, the compiler will automatically add null characters at the end.

Multidimensional arrays are initialized in the same way as one-dimensional arrays. For example, the following formula initializes sqrs from 1 to 1 0 and their respective squares.

int sqrs[ 10][2]={

1, 1,

2,4,

3,9,

4, 1 6 ,

5,2 5 ,

6,3 6,

7,4 9 ,

8,6 4 ,

9,8 1,

1 0, 1 0 0 ,

} ;

5.4.2 Initialization of Variable Length Arrays

Imagine using the method of array initialization to establish an error information table as follows:

Char e 1[ 12] = "read error \ n ";;

Char e2[ 13] = "Write error \ n ";;

Char e3[ 18] = "Cannot open file \ n ";;

You can imagine how troublesome it is to manually calculate the number of characters in each message to determine the length of the array. C can automatically calculate the length of an array by initializing a variable-length array. The initialization of variable-length array is to let C compiler automatically create an array of unspecified length large enough to store initialization data. Using this method, the above information table becomes:

Char e 1[] = "read error \ n ";;

Char e2[] = "Write error \ n ";;

Char e3[] = "Cannot open file \ n ";;

Given the above initialization, the following statement printf ("%haslength% d \ n ",e2, sizeof(E2)););

Will print out:

Write error

The length is 13.

In addition to reducing trouble, the application of variable-length array initialization enables programmers to modify any information without worrying about possible calculation errors at any time.

The initialization method of variable-length array is not limited to one-dimensional array. However, when initializing a multidimensional array, you must specify division.

The length of other dimensions except the first dimension so that the compiler can retrieve the array correctly. Its method is the same as that of array parameters.

The instructions are similar. In this way, a variable-length table can be established, and the compiler automatically allocates storage space for it. For example, the following is used

The method of initializing variable-length arrays defines the array sqrs:

int sqrs[ ][2]={

1, 1,

2,4,

3,9,

4, 1 6,

5,2 5,

6,3 6,

7,4 9,

8,6 4,

9,8 1,

1 0, 1 0 0

} ;

Compared with the initialization of fixed-length array, the advantage of this description is that the length of the table can be increased or shortened at any time without changing the length of each dimension of the array.

5.5 Application Example

[Example 5-6] Score the contestants.

Calculation method: Deduct the highest score and the lowest score from the score of 65,438+00 judges, then divide the total score by 8, and finally get the final score of the player (the score is 100%).

# include & ltstdio.h & gt

Master ()

{

Int score [10]; /* 10 judges' scores */

Buoy; /* Final score */

int I;

int max =- 1; /* Maximum score */

int min = 10 1; /* Minimum score */

int sum = 0; /*/kloc-the sum of 0/0 judges */

for(I = 0; I< 10; i ++)

{

Printf ("Please enter the score ofNo. %d", I+1);

scanf("%d\n ",& ampscore[I]);

sum = sum+score[I];

}

for(I = 0; I< 10; i++)

{

if(score[I]& gt; Max)

max = score[I];

}

for(I = 0; I< 10; i++)

{

if(score[I]& lt; Minimum)

min = score[I];

}

mark =(sum-min-max)/8.0;

Printf ("Player's logo is %. 1f\n", mark);

}

[Example 5-7] Sequencing: Sequences with 5 numbers are sorted by selection method.

The algorithm idea of the selection method is: (descending)

1. Put the number n to be sorted into the array num, namely num[0], num[ 1], num[n- 1].

2. compare num[ 0] with the following num[ 1] ... num[ n- 1] in turn to ensure that the large number comes first and the decimal number comes last. In this comparison, num[0] is the largest in the array.

3. The remaining n- 1 elements

4. The serial number [1] and serial number [2]...num[ n- 1] are compared in turn, with the largest before the decimal number, and this num[ 1] is the largest of all elements.

Compared with num[ n-2], num[ n- 1] holds a larger number.

Num[ n- 1] stores decimals. After comparison, they are arranged in order.

Example: The number of 5 s to be sorted is: 44 76 82 63 7 1.

One trip ranking: 1 comparison: 76 44 82 63 7 1

Two comparisons: 82 44 76 63 7 1

Comparison: 82 44 76 63 7 1

Four comparisons: 82 44 76 63 7 1

highest

# include & ltstdio.h & gt

Master ()

{

int num[5];

int i,j;

Internal temperature;

num[0]= 94; num[ 1]= 76; num[2]= 82; num[3]= 63; num[4]= 7 1;

for(I = 0; I<4; i++)

for(j = I+ 1; j & lt5; j++)

{

if(num[I]& gt; Number [j])

{

temp = num[I];

Number [i] = number [j];

num[j]= temp;

}

}

for(I = 0; I<5; i++)

printf("%4d ",num[I]);

printf(" ok \ n ");

}

This is a very simple sorting program, and we can compile many powerful management programs with a little expansion, such as the total score of students, the average ranking of scores and so on.

[Example 5-8] A simple inquiry system for students' grades.

Figure 5-3 shows the student achievement registration form. The following sample program completes the following functions:

1) According to the input student number, the test scores and average scores are given;

2) Print out the test scores of each student according to the input test times, and give the average score;

3) Find out students' test scores according to their numbers;

4) Enter the test scores.

# include & ltstdio.h & gt

Master ()

{

int select

int i,j;

Int score [5] [7];

int average = 0;

int sum = 0;

Do {

Printf ("This program has four functions \ n");

Printf(" 1, query students' grades according to their student numbers \ n ");

Printf("2, according to the statistical results of test times \ n ");

Printf("3, query results according to test number and student number \ n ");

Printf("4, grade entry \ n ");

Printf("0,exit \ n ");

Printf ("Please enter a choice (0-4):");

Scanf("%d\n ",& select);

Switch (selection)

{

Case 0:

printf(" OK \ n ");

Exit (0)

Break;

Case 1:

Printf ("Enter student number:");

scanf("%d\n ",& ampI);

for(j = 1; j & lt7; j++)

{

Printf ("Grade %d is %d\n ",j,score[I][j]);

sum+= score[I][j];

}

Average value = sum/6;

Printf ("Average grade of students is %d\n", average);

Break;

Case 2:

Printf ("Enter exam number:");

scanf("%d\n ",& ampj);

for(I = 1; I<5; i++)

{

Printf ("The undergraduate grade of student # %d is %d\n", i, score [i] [j]);

sum+= score[I][j];

}

Average value = sum/4;

Printf ("average undergraduate grade is %d\n", average);

Break;

Case 3:

Printf ("Enter student number and test number:");

Scanf("%d %d\n ",&, me, & ampj);

Printf ("Student %d gets %d \ n", I, j, score [I] [j]);

Break;

Case 4:

Printf ("Please enter grades \ n");

for(I = 1; I<5; i++)

for(j = 1; j & lt7; j++)

scanf("%d\n ",& ampscore[I][j]);

Break;

Default value:

Break;

} while( 1);

}

As can be seen from this example, when two-dimensional arrays are involved, double for loops are usually used to access elements.