当前位置:网站首页>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.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
4. Arrays as function arguments
5. Program instance ( Gobang and Minesweeper )()
1. One dimensional array creation and initialization .
1.1. Array creation
type_t arr_name [const_n];type_t Is the element type of the exponential groupconst_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 initializedthe second It is called incomplete initialization , Only the first three elements are initialized , The remaining seven elements are initialized to by default 0Third Is to quickly initialize all ten elements to 0The 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 hasThe fifth one Array initialization has only one element 0Sixth 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 meansThe eighth And fourth 、 Five similar items are initialized , To determine how many elements he hasThe 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
1.3. The use of one-dimensional arrays

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 .
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

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 :
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



Conclusion :
1. In our sense, a two-dimensional array is multi row and multi column , However, in practice, the addresses in memory are continuous
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 :
...... | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | ............ | |||||
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



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
5. Program instance ( Gobang and Minesweeper )()
5.1. Sanzi

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

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 :
边栏推荐
- C # get all callable methods of WebService interface [webmethod]
- 推荐的图片临时在线压缩工具
- Analysis on the similarities and differences of MVC, MVP and mvvc
- [LeetCode]-滑动窗口
- Implementation of article list function on PHP 18 home page
- C盘无损移动文件
- C disk lossless move file
- Returns the width and height of an element
- Tita:新锐集团采用一对一面谈推动绩效变革成功
- Conception d'un système basé sur MVC avec javaswing JDBC
猜你喜欢
Collection of wrong questions in soft test -- morning questions in the first half of 2011
Analysis of scoped attribute principle and depth action selector
【JS解决】leedcode 200. 岛屿数量
Day 007: go language string
[flutter problem Series Chapter 67] the Solution to the problem of Routing cannot be jumped again in in dialog popup Using get plug - in in flutter
Introduction to applet Basics (dark horse learning notes)
Colab tutorial (super detailed version) and colab pro/pro+ evaluation
利用Javeswingjdbc基于mvc设计系统
Small program imitating Taobao Jiugong grid sliding effect
用navicat将mysql数据转化为postgresql
随机推荐
SS selector
Latex operation
Force buckle 25 A group of K flipped linked lists
php开发14 友情链接模块的编写
Avantages de win8.1 et win10
Four methods for judging JS data types and user-defined methods
Design system based on MVC using javeswingjdbc
NodeJS 解析 GET 请求 url 字符串
2022 question bank and answers for operation certificate examination of safety production management personnel in road transport enterprises
前几年的互联网人vs现在的互联网人
Blockly learning ----2 Code generation, grid, scaling, events, storage
Li Kou brush question 338 Bit count
第三方评论插件
rust编程-链表:使用struct实现链表,使用堆合并k个升序链表,自定义Display
How to implement a custom jdbc driver in only four steps?
C#获取WebService接口的所有可调用方法[WebMethod]
Analysis on the similarities and differences of MVC, MVP and mvvc
是“凯撒密码”呀。(*‘▽‘*)*
Common skills in embedded programming
2022 ICML | Pocket2Mol: Efficient Molecular Sampling Based on 3D Protein Pockets