当前位置:网站首页>Section 4 - arrays

Section 4 - arrays

2022-06-13 04:47:00 Stretch the curtain with the wind

Catalog

1. One dimensional array creation and initialization .

1.1. Array creation

1.2. Initialization of an array

1.3. The use of one-dimensional arrays

1.4.  One dimensional array storage in memory

2. The creation and initialization of two-dimensional array

2.1 The creation of two-dimensional array

2.2 Initialization of 2D array

2.3 The use of two-dimensional arrays

 2.4 Two dimensional array storage in memory

3. An array

4. Arrays as function arguments

4.1. Bubble sort example ()

4.2. What is the array name

5. Program instance ( Gobang and Minesweeper )()

5.1. Sanzi

5.2. The Minesweeper game


1. One dimensional array creation and initialization .

1.1. Array creation

An array is a collection of elements of the same type .
How to create an array :
type_t   arr_name   [const_n];
type_t Is the element type of the exponential group
const_n Is a constant expression , Used to specify the size of an array
int arr1[10];
char arr3[10];
float arr4[1];
double arr5[20];

int count = 10;
int arr2[count];   //VS You cannot create arrays like this in the compiler 

notes : Array creation , stay C99 Before standard , [ ] I want to give one Constant Can only be , You can't use variables . stay C99 The standard supports the concept of variable length arrays .(VS Yes C99 Standard support is not good enough )( Variable length arrays cannot be initialized when they are created in other compilers that support variable length arrays )

1.2. Initialization of an array

The initialization of an array refers to , While creating an array, give the contents of the array some reasonable initial values ( initialization ).

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

char arr4[3] = {'a',98, 'c'};          //7
char arr5[] = {'a','b','c'};           //8
char arr6[] = "abcdef";                //9
first Is fully initialized
the second It is called incomplete initialization , Only the first three elements are initialized , The remaining seven elements are initialized to by default 0
Third Is to quickly initialize all ten elements to 0
The fourth one If you do not set the array size , Then it will be initialized according to the content , To determine how many elements he has
The fifth one Array initialization has only one element 0
Sixth If the array is not initialized , So the contents are random values ( Don't suggest )
Seventh No problem with arrays , among 98 Namely b Of ASCII value , There is actually a character in it b It means
The eighth And fourth 、 Five similar items are initialized , To determine how many elements he has
The ninth Is to use a string to initialize a character array , So strings can initialize character arrays
char arr1[]={'a','b','c'};
char arr2[]="abc";

The first array has 3 Characters 'a' 'b' 'c', Occupy 3 Bytes ; The length is uncertain ; Output is abc+ The statement

The second array has 4 Characters 'a' 'b' 'c' '\0', Occupy 4 Bytes ; The length is 3; Output is abc

notes :
1.strlen It's a library function , It calculates the length of the string , And only for strings , The concern is whether there is... In the string '\0', The calculation is '\0' The number of characters before
2.sizeof Is an operator ( Operator ),sizeof Is used to calculate the memory space occupied by variables , Any type can be used, focusing only on space size , I don't care if there is... In memory '\0'

1.3. The use of one-dimensional arrays

For the use of arrays, we introduced an operator : [ ] , Subscript reference operator . It's actually an array access operator .

  notes :

1. When accessing an element of an array [ ] Can be a variable , When specifying the size of an array, it must be a constant .

2.  Arrays are accessed using subscripts , The subscript is from 0 Start .

3. The size of the array can be calculated .

1.4.  One dimensional array storage in memory

Knowledge point 1 :

Code :

Conclusion :

1. There is a difference in address between every two elements 4, Because the size of an integer element is 4 Bytes , One byte uses one address , So the address difference between every two adjacent elements 4.

2. One dimensional arrays are stored continuously in memory .

3. Arrays grow with subscripts , The address changes from low to high

Knowledge point two :

  Conclusion : as long as p Points to the address of the first element of the array ( The address of the first element is the smallest of the four bytes ), Because here p It's an integer pointer , to p+1 Just skip. 4 An address ( byte ), Point to the address of the second element ( The second element is the smallest of the four addresses ), therefore p+i Namely arr[i] The address of .

Knowledge point three :

Conclusion : We can no longer access arrays in the form of subscripts , Use *(p+i) The subscript is i Array elements of , Where dereference * Is to access an integer space ( Four bytes ) Size .
 

2. The creation and initialization of two-dimensional array

2.1 The creation of two-dimensional array

int arr[3][4];
char arr[3][5];
double arr[2][4];

2.2 Initialization of 2D array

int arr[3][4] = { 1,2,3,4,5,6,7,8,9,10,11,12 };
int arr[3][4] = { 1,2,3,4,5,6,7};
int arr[3][4] = { {1,2},{3,4},{5,6} };
int arr[][]={1,2,3,4,5,6,7,8,9,10,11,12};   // error 
int arr[][4]={1,2,3,4,5,6,7,8,9,10,11,12};  // correct 

The first is full initialization : The first line of elements 1 2 3 4 , The second element 5 6 7 8, The third line element 9 10 11 12

The second is incomplete initialization : The first line of elements 1 2 3 4 , The second element 5 6 7 0, The third line element 0 0 0 0

The third is to initialize each row separately : The first line of elements 1 2 0 0, The second element 3 4 0 0, The third line element 5 6 0 0

The fourth initialization method is wrong , Because of this 12 Elements can be thought of as 3 That's ok 4 Column ,2 That's ok 6 Column and so on , Not only

The fifth one is correct , Because if you specify the number of columns, you know how many elements there are in a row , The result is the only .

notes : Rows of a two-dimensional array can be omitted , Columns cannot be omitted .( It is impossible to have rows without columns )

2.3 The use of two-dimensional arrays

Two dimensional arrays are also used by subscripts

 2.4 Two dimensional array storage in memory

Knowledge point 1 :
The image is expressed as :
Theoretically , We think that the two-dimensional array is the following figure
actually , It is stored in memory as shown in the following figure

  Conclusion :

1. In our sense, a two-dimensional array is multi row and multi column , However, in practice, the addresses in memory are continuous

2. We call the one-dimensional array in the first row arr[0], The one-dimensional array in the second row is called arr[1], The one-dimensional array in the third row is called arr[2], So a two-dimensional array can be understood as an array of a one-dimensional array

3. An array

The subscript of an array is range limited .
The next stipulation of the array is from 0 At the beginning , If the array has n Elements , The subscript of the last element is n-1.
So if the subscript of the array is less than 0, Or greater than n-1, The array is accessed out of bounds , Access beyond the legal space of the array .
C The language itself does not check the bounds of array subscripts , The compiler does not necessarily report an error , But the compiler does not report an error , That doesn't mean the program is right , So when programmers write code , You'd better do cross-border inspection yourself .
Array out of bounds on a one-dimensional array 、 Two dimensional arrays may be out of bounds

  notes : The above figure is an example of an array out of bounds .arr The array only has 10 Elements , The subscript is 0-9, and for Cycle to 10 Subscript assignment , The first 10 Subscripts are not the contents of the array , So the array is out of bounds . Here's the picture :

......0123456789............
Other memory space arr Array memory space Other memory space


Prompt of out of range error :(c The language syntax has no ability to check the array out of bounds , The compiler will check it , But the ability is also limited , Sometimes it can't be identified, such as the second one below )

1. At the arrow arr Is the name of the array you crossed :

 

2. There is no error reported by the system , But the output is wrong .


4. Arrays as function arguments

4.1. Bubble sort example ()

describe :
Design a function pair arr Array to sort
Bubble sort idea :(n The elements need n-1 Bubble sorting ; First sort n The elements need n-1 Compare it to , Second sort last fixed ,n-1 The elements need n-2 Compare it to , And so on )
Code :
notes :
1. When passing parameters to an array , Arguments can only use array names
2. When passing parameters to an array , The formal parameter can be int(char etc. ) arr[ ]( Array name )   or int*(char* etc. ) arr( Pointer variable name ), The two are exactly the same .
3. Here we can see arr[i] and p[i]( here p Is the address of the first element of the array ) It's the same , Here's the picture , All arrays use p[i] In the form of .( Actually arr Itself is the address of the first element , The two are exactly the same in nature )
4. In fact, the array parameter does not pass the entire array , The address of the first element of the array is passed .

5. When the array passes parameters, it passes the address of the first element , Write arr[0] In fact, you can find the address of the first element through this address . That is, in the main function , The function name can represent the array , It also means the address of the first element . When a function calls an array , Whether the formal parameter is received as a pointer or as arr[ ] This form of array receives ( These two forms have exactly the same meaning and function ), Only the address of the first element of the array is received , It's just that you can find it in the function by the address of the first element of the array arr[1] And so on , So you can also use... In functions arr[1] etc. .

6. The array name is equivalent to the address , So the time of transmission is the address , Equivalent to address calling .


4.2. What is the array name

  Conclusion : The array name is the address of the first element of the array ( There are two exceptions )

exception :
1. sizeof Put a separate array name inside , The array name represents the entire array ,sizeof( Array name ) It calculates the size of the entire array , Unit is byte .( Does not hold in function )
2. & Array name , The array name represents the entire array , It takes out the address of the entire array
notes : The address of the array printed out is actually the address of the first element of the array , But there is a difference , as follows , Add... To the address of an array 1, Is to add the size of the entire array , There is a 20, the reason being that 5 An integer element .

 


5. Program instance ( Gobang and Minesweeper )()

5.1. Sanzi

File allocation :

 test.c Code :

#define _CRT_SECURE_NO_WARNINGS 1

#include "game.h"

void menu()
{
	printf("************************\n");
	printf("*****   1. play   ******\n");
	printf("*****   0. exit   ******\n");
	printf("************************\n");
}

void game()
{
	// The data is stored in a two-dimensional array of characters , Players play chess '*', Computer chess is '#',
	char board[ROW][COL] = { 0 };// The contents of the array should be all spaces 
	InitBoard(board, ROW, COL);// Initialize chess and cards 
	// Print chessboard 
	DisplayBoard(board, ROW, COL);
	// Playing chess 
	char ret = 0;
	while (1)
	{
		player_move(board, ROW, COL);
		DisplayBoard(board, ROW, COL);
		ret = is_win(board, ROW, COL);
		if (ret != 'C')
		{
			break;
		}
		computer_move(board, ROW, COL);
		DisplayBoard(board, ROW, COL);
		ret = is_win(board, ROW, COL);
		if (ret != 'C')
		{
			break;
		}
	}
	if (ret == '*')
	{
		printf(" Game player wins \n");
	}
	else if (ret == '#')
	{
		printf(" Computers win \n");
	}
	else
	{
		printf(" It ends in a draw \n");
	}
}


void test()
{
	int input = 0;
	srand((unsigned int)time(NULL));
	do
	{
		menu();
		printf(" Please select :>");
		scanf("%d", &input);
		switch (input)
		{
		case 1:
			game();
			break;
		case 0:
			printf(" Quit the game \n");
			break;
		default:
			printf(" Wrong choice \n");
			break;
		}

	} while (input);
}

int main()
{
	test();

	return 0;
}

game.c Code :

#define _CRT_SECURE_NO_WARNINGS 1

#include "game.h"

void InitBoard(char board[ROW][COL], int row, int col)
{
	int i = 0;
	int j = 0;
	for (i = 0; i < row; i++)
	{
		for (j = 0; j < col; j++)
		{
			board[i][j] = ' ';
		}
	}
}

// edition 1
//void DisplayBoard(char board[ROW][COL], int row, int col)
//{
//	int i = 0;
//	int j = 0;
//	for (i = 0; i < row; i++)
//	{
//		// data 
//		printf(" %c | %c | %c \n", board[i][0], board[i][1], board[i][2]);
//		// Split line 
//		if(i<row-1)
//			printf("---|---|---\n");
//	}
//}


// edition 2
void DisplayBoard(char board[ROW][COL], int row, int col)
{
	int i = 0;
	int j = 0;
	for (i = 0; i < row; i++)
	{
		// data 
		for (j = 0; j < col; j++)
		{
			printf(" %c ", board[i][j]);
			if (j < col - 1)
				printf("|");
		}
		printf("\n");
		// Split line 
		if (i < row - 1)
		{
			for (j = 0; j < col; j++)
			{
				printf("---");
				if (j < col - 1)
					printf("|");
			}
		}
		printf("\n");
	}
}


// Players play chess 
void player_move(char board[ROW][COL], int row, int col)
{
	printf(" Players play chess :>");
	int x = 0;
	int y = 0;

	while (1)
	{
		scanf("%d %d", &x, &y);
		if (x >= 1 && x <= row && y >= 1 && y <= col)
		{
			if (board[x - 1][y - 1] == ' ')
			{
				board[x - 1][y - 1] = '*';
				break;
			}
			else
			{
				printf(" The coordinates are occupied , Please re-enter !\n");
			}
		}
		else
		{
			printf(" Illegal coordinates , Please re-enter !\n");
		}
	}
}



void computer_move(char board[ROW][COL], int row, int col)
{
	int x = 0;
	int y = 0;
	printf(" The computer plays chess >\n");
	while (1)
	{
		x = rand() % ROW;//0~2
		y = rand() % COL;//0~2
		if (board[x][y] == ' ')
		{
			board[x][y] = '#';
			break;
		}
	}
}

int is_full(char board[ROW][COL], int row, int col)
{
	int i = 0;
	int j = 0;
	for (i = 0; i < row; i++)
	{
		for (j = 0; j < col; j++)
		{
			if (board[i][j] == ' ')
			{
				return 0;
			}
		}
	}
	return 1;
}

char is_win(char board[ROW][COL], int row, int col)
{
	int i = 0;
	// Three elements 
	for (i = 0; i < row; i++)
	{
		if (board[i][0] == board[i][1] && board[i][1] == board[i][2] && board[i][1] != ' ')
		{
			return board[i][1];
		}
	}
	// The three column 
	for (i = 0; i < col; i++)
	{
		if (board[0][i] == board[1][i] && board[1][i] == board[2][i] && board[1][i] != ' ')
		{
			return board[1][i];
		}
	}
	// Diagonal judgment 
	if (board[0][0] == board[1][1] && board[1][1] == board[2][2] && board[1][1] != ' ')
	{
		return board[1][1];
	}

	if (board[0][2] == board[1][1] && board[1][1] == board[2][0] && board[1][1] != ' ')
	{
		return board[1][1];
	}

	// Judge a draw 
	if (1 == is_full(board, row, col))
	{
		return 'Q';
	}
	// continue 
	return 'C';
}

game.h Code :

#define _CRT_SECURE_NO_WARNINGS 1
#pragma once

#include <stdio.h>
#include <time.h>
#include <stdlib.h>

#define ROW 3
#define COL 3


// Initialize chessboard 
void InitBoard(char board[ROW][COL], int row, int col);

// Print chessboard 
void DisplayBoard(char board[ROW][COL], int row, int col);

// Players play chess 
void player_move(char board[ROW][COL], int row, int col);

// The computer plays chess 
void computer_move(char board[ROW][COL], int row, int col);

// The code to judge whether to win or lose 
// Game player wins  - '*'
// Computers win  - '#'
// Average  --- 'Q'
// continue  ----'C'

char is_win(char board[ROW][COL], int row, int col);

Running results :

5.2. The Minesweeper game

  File allocation :

 test.c Code :

#define _CRT_SECURE_NO_WARNINGS 1


#include "game.h"

void menu()
{
	printf("***********************\n");
	printf("*****  1. play     ****\n");
	printf("*****  0. exit     ****\n");
	printf("***********************\n");
}


void game()
{
	// Create array 
	char mine[ROWS][COLS] = { 0 };// Store the information of the arranged mine 
	char show[ROWS][COLS] = { 0 };// Store the information of the detected mine 

	// initialization mine The array is full '0'
	InitBoard(mine, ROWS, COLS, '0');
	// initialization show The array is full '*'
	InitBoard(show, ROWS, COLS, '*');

	// Print chessboard 
	//DisplayBoard(mine, ROW, COL);

	// Arrange thunder 
	SetMine(mine, ROW, COL);
	DisplayBoard(show, ROW, COL);

	//DisplayBoard(mine, ROW, COL);
	// Demining 
	FindMine(mine, show, ROW, COL);
}

void test()
{
	int input = 0;
	srand((unsigned int)time(NULL));

	do
	{
		menu();
		printf(" Please select :>");
		scanf("%d", &input);
		switch (input)
		{
		case 1:
			// Mine clearance 
			game();
			break;
		case 0:
			printf(" Quit the game \n");
			break;
		default:
			printf(" Wrong choice \n");
			break;
		}
	} while (input);
}

int main()
{
	test();
	return 0;
}

game.c Code :

#define _CRT_SECURE_NO_WARNINGS 1

#include "game.h"


void InitBoard(char board[ROWS][COLS], int rows, int cols, char set)
{
	int i = 0;
	int j = 0;
	for (i = 0; i < rows; i++)
	{
		for (j = 0; j < cols; j++)
		{
			board[i][j] = set;
		}
	}
}


void DisplayBoard(char board[ROWS][COLS], int row, int col)
{
	//1~9
	int i = 0;
	int j = 0;

	// Printing of column numbers 
	for (i = 0; i <= col; i++)
	{
		printf("%d ", i);
	}
	printf("\n");

	for (i = 1; i <= row; i++)
	{
		printf("%d ", i);// Print line number 

		for (j = 1; j <= col; j++)
		{
			printf("%c ", board[i][j]);
		}
		printf("\n");
	}
}

void SetMine(char mine[ROWS][COLS], int row, int col)
{
	int count = EASY_COUNT;

	while (count)
	{
		int x = rand() % row + 1;
		int y = rand() % col + 1;

		if (mine[x][y] == '0')
		{
			mine[x][y] = '1';
			count--;
		}
	}
}

static int get_mine_count(char mine[ROWS][COLS], int x, int y)
{
	return mine[x - 1][y] +
		mine[x - 1][y - 1] +
		mine[x][y - 1] +
		mine[x + 1][y - 1] +
		mine[x + 1][y] +
		mine[x + 1][y + 1] +
		mine[x][y + 1] +
		mine[x - 1][y + 1] - 8 * '0';
}


void FindMine(char mine[ROWS][COLS], char show[ROWS][COLS], int row, int col)
{
	int x = 0;
	int y = 0;
	int win = 0;

	while (win < row * col - EASY_COUNT)
	{
		printf(" Please enter the coordinates to be checked :>");
		scanf("%d %d", &x, &y);
		if (x >= 1 && x <= row && y >= 1 && y <= col)
		{
			if (mine[x][y] == '1')
			{
				printf(" I'm sorry you were killed \n");
				DisplayBoard(mine, row, col);
				break;
			}
			else
			{
				// Calculation x,y There are several mines around the coordinates 
				int n = get_mine_count(mine, x, y);
				show[x][y] = n + '0';
				DisplayBoard(show, row, col);
				win++;
			}
		}
		else
		{
			printf(" It's illegal to enter coordinates , Can't mine , Please re-enter \n");
		}
	}
	if (win == row * col - EASY_COUNT)
	{
		printf(" congratulations , Mine clearance is successful \n");
		DisplayBoard(mine, row, col);
	}

}

game.h Code :

#pragma once

// The header file contains 
#include <stdio.h>
#include <time.h>
#include <stdlib.h>

// Declaration of symbols 
#define ROW 9
#define COL 9

#define ROWS ROW+2
#define COLS COL+2

#define EASY_COUNT 10

// Declaration of functions 

// Initialize chessboard 
void InitBoard(char board[ROWS][COLS], int rows, int cols, char set);

// Print chessboard 
void DisplayBoard(char board[ROWS][COLS], int row, int col);

// Arrange thunder 
void SetMine(char mine[ROWS][COLS], int row, int col);

// Check the thunder 
void FindMine(char mine[ROWS][COLS], char show[ROWS][COLS], int row, int col);

Running results :

原网站

版权声明
本文为[Stretch the curtain with the wind]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202280520088751.html