当前位置:网站首页>C language series - Section 4 - arrays
C language series - Section 4 - arrays
2022-06-23 02:23:00 【Unity of knowledge and action, brother Hao】
Array
1. One dimensional array creation and initialization
1.1 Array creation
An array is a set of Elements of the same type Set .
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
An instance created by an array :
// Code 1
int arr1[10];/* Uninitialized array */
Be careful :
/* If the array is defined in a function ,( It is defined in the stack area )( understand ), Will be randomly defined value . But if defined in a global variable , Or use statistic Definitions are not randomly defined Initial value , A character array char The default is \0, integer array int The default is 0*/
// Code 2
int count = 10;
int arr2[count];
// Arrays can be created normally ?
Can not be , Variables cannot be used to define array sizes
Unless with const Define constants
const int count = 10;
// Code 3
char arr3[10];
float arr4[1];
double arr5[20];
Be careful :
Such as code 1
// Code 4
char a = 87;
printf("%c",a); The output is ascll In code 87 The corresponding character
Add : Uninitialized array
as follows
char a[3] = {
'a','b','c'};// There is no value in the back
char b[5] = {
'e','d','f'};// Wherever defined , The first 4 The default is... In the future \0
char c[3] = "abc"; // This is not allowed , Because the string is followed by '\0'
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 ).
Look at the code
int arr1[10] = {
1,2,3}; // Not fully initialized
int arr2[] = {
1,2,3,4}; /* Initialization of unknown size , But after initialization , Convenient and accurate Fixed size . After this definition ,arr2 The array is 4 individual , It can no longer be expanded */
int arr3[5] = {
1,2,3,4,5};
char arr4[3] = {
'a',98, 'c'};
char arr5[] = {
'a','b','c'};
char arr6[] = "abcdef"; // Note that 7 individual
If you want to create an array without specifying the size of the array, you have to initialize it . The number of elements of the array depends on the initialized Content To make sure .
But for the following code to distinguish , How to allocate in memory .
char arr1[] = "abc"; // Note that this definition is 4 Characters ( At the end of the string is \0)
char arr2[3] = {
'a','b','c'};
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 .
So let's look at the code :
#include <stdio.h>
int main()
{
int arr[10] = {
0 };// Incomplete initialization of arrays
// Count the number of elements in an array
int sz = sizeof(arr) / sizeof(arr[0]);
// Assign values to the contents of the array , Arrays are accessed using subscripts , Subscript from 0 Start . therefore :
int i = 0;// Do subscripts
for (i = 0; i < 10; i++)// Write here 10, Ok or not ?
{
arr[i] = i;
}
// Output the contents of the array Output an array with a loop ( String direct output is available %s)
for (i = 0; i < 10; ++i)
{
printf("%d ", arr[i]);
}
return 0;
}
summary :
- Arrays are accessed using subscripts , The subscript is from 0 Start .
- The size of the array can be calculated .
1.4 One dimensional array storage in memory
Next, we discuss the storage of arrays in memory .
Look at the code :
#include <stdio.h>
int main()
{
int arr[10] = {
0 };
int i = 0;
int sz = sizeof(arr) / sizeof(arr[0]);
for (i = 0; i < sz; ++i)
{
printf("&arr[%d] = %p\n", i, &arr[i]);
}
return 0;
}
/* Be careful :%p Is used to output the address . Output found , Each address differs by 4 Bytes */
The output is as follows 
Watch the output carefully , We know , As the array subscript grows, the address of the element , It's also increasing regularly .
So we can draw a conclusion : Arrays are continuously stored in memory .
And the bytes occupied by each value , Determined by the array type
2. The creation and initialization of two-dimensional array
2.1 The creation of two-dimensional array
// Array creation
int arr[3][4];
char arr[3][5];
double arr[2][4];
2.2 Initialization of 2D array
// Array initialization
int arr[3][4] = {
1,2,3,4};
int arr[3][4] = {
{
1,2},{
4,5}};
int arr[][4] = {
{
2,3},{
4,5}};
If the two-dimensional array is initialized , Lines can be omitted , Columns cannot be omitted
2.3 The use of two-dimensional arrays
Two dimensional arrays are also used by subscripts .
Look at the code :
#include <stdio.h>
int main()
{
int arr[3][4] = {
0 };
int i = 0;
for (i = 0; i < 3; i++)
{
int j = 0;
for (j = 0; j < 4; j++)
{
arr[i][j] = i * 4 + j;
}
}
for (i = 0; i < 3; i++)
{
int j = 0;
for (j = 0; j < 4; j++)
{
printf("%d ", arr[i][j]);
}
}
return 0;
}
2.4 Two dimensional array storage in memory
Like a one-dimensional array , Here we try to print each element of a two-dimensional array .
#include <stdio.h>
int main()
{
int arr[3][4];
int i = 0;
for (i = 0; i < 3; i++)
{
int j = 0;
for (j = 0; j < 4; j++)
{
printf("&arr[%d][%d] = %p\n", i, j, &arr[i][j]);
}
}
return 0;
}
The output is as follows :
Through the results, we can analyze , In fact, two-dimensional arrays are also stored continuously in memory .
And the bytes occupied by each value , Determined by the array type
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, Namely Array out of bounds access , 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 .
#include <stdio.h>
int main()
{
int arr[10] = {
1,2,3,4,5,6,7,8,9,10};
int i = 0;
for(i=0; i<=10; i++)
{
printf("%d\n", arr[i]);
// When i be equal to 10 When , Cross border visit
}
return 0; }

Rows and columns of two-dimensional arrays may also be out of bounds .
4. Arrays as function arguments
Often when we write code , Will pass the array as an argument to a function , such as : I want to implement a bubble sort ( Here is the idea of algorithm ) function
Bubble sort :
Sort an integer array .
Bubble sort algorithm ( Super detailed )
4.1 Wrong design of bubble sort function
// Method 1:
#include <stdio.h>
void bubble_sort(int arr[])
{
int sz = sizeof(arr) / sizeof(arr[0]);
// Is that right ?
/* incorrect , because arr【】 The address is accepted , thereafter arr It means The address of the first element */
int i = 0;
for (i = 0; i < sz - 1; i++)
{
int j = 0;
for (j = 0; j < sz - i - 1; j++)
{
if (arr[j] > arr[j + 1])
{
int tmp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = tmp;
}
}
}
}
int main()
{
int arr[] = {
3,1,7,5,8,9,0,2,4,6 };
bubble_sort(arr);// Whether it can be sorted normally ?
for (i = 0; i < sizeof(arr) / sizeof(arr[0]); i++)
{
printf("%d ", arr[i]);// The output is not ordered
}
return 0;
}
therefore , Arrays as function arguments , It is accepted that Array first address
4.2 Correct design of bubble sorting function
#include <stdio.h>
void bubble_sort(int arr[],int sz)
{
int i = 0;
for (i = 0; i < sz - 1; i++)
{
int j = 0;
for (j = 0; j < sz - i - 1; j++)
{
if (arr[j] > arr[j + 1])
{
int tmp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = tmp;
}
}
}
}
int main()
{
int arr[] = {
3,1,7,5,8,9,0,2,4,6 };
int i;
bubble_sort(arr, sizeof(arr) / sizeof(arr[0]));
for (i = 0; i < sizeof(arr) / sizeof(arr[0]) ;i++)
{
printf("%d ", arr[i]);
}
return 0;
}
4.3 What is the array name ?
#include <stdio.h>
int main()
{
int arr[10] = {
1,2,3,4,5 };
printf("%p\n", arr);
printf("%p\n", &arr[0]);
printf("%d\n", *arr);
// Output results
return 0;
}

Conclusion :
The array name is the address of the first element of the array .( There are two exceptions )
4.3 The array name is a special case of the address of the first element of the array
special case
int arr[10] = {
0};
printf("%d\n", sizeof(arr));
The output is 40
special case :
- sizeof( Array name ), Calculate the size of the entire array ,sizeof Put a separate array name inside , The array name represents the entire array .
- & Array name , What we get is the address of the array .& Array name , The array name represents the entire array
Such as :
int a[10];
&a -> Represents the address of the entire array
&a+1 Will cross the border

In addition to this 1,2 Except for two cases , All array names represent arrays First element The address of .
5. Data instance
5.1 Application examples of arrays 1: Sanzi
5.2 Application examples of arrays 2: The Minesweeper game
C Language minesweeps (vs Engineering function reflects )( Logic is important )
边栏推荐
- Performance test -- Jenkins environment construction for 15jmeter performance test
- Buuctf misc-[bjdctf2020] Nani
- //1.15 putchar function
- Lying in the trough, write it yourself if you can't grab it. Use code to realize a Bing Dwen Dwen. It's so beautiful
- Targeted and ready to go
- The practice of traffic and data isolation in vivo Reviews
- Deep learning environment configuration (III) pytorch GPU under Anaconda
- //1.17 printf function
- How PHP uses redis
- Performance test -- 14 detailed explanation of performance test report and precautions
猜你喜欢

Nebula operator cloud practice

Interviewer: what is the difference between SSH and SSM frameworks? How to choose??

Freshman C language summary post (hold change) Part 2 formatted monthly calendar

Anaconda creates a new environment encounter pit

II Data preprocessing

Microservice Optimization: internal communication of microservices using grpc

Branch and loop statements (including goto statements) -part1

Circuit analysis (circuit principle)

Classical questions of function recursion

WebService details
随机推荐
Why is BeanUtils not recommended?
Error in OpenCV image operation: error: (-215:assertion failed)_ src. empty() in function ‘cv::cvtColor‘
Xgboost Guide
Special exercise split line-----------------------------
Problem thinking and analysis process
EDI project cases of customers in medical device industry
My good brother gave me a difficult problem: retry mechanism
//1.14 comma operator and comma expression
About the use of mock framework
Schedule tasks to periodically restart remote services or restart machines
JS case: support canvas electronic signature function on PC and mobile
Garbled code of SecureCRT, double lines, double characters, unable to input (personal detection)
Common mistakes in C language (sizeof and strlen)
How to download online printing on Web pages to local PDF format (manual personal test)
pd. read_ CSV and np Differences between loadtext
[target tracking] open source | polytrack: use boundary polygons to quickly track and segment multiple targets, instead of bounding box and mask tracking
Arm assembly syntax
WM view of commodity master data in SAP retail preliminary level
Interviewer: with the for loop, why do you need foreach??
Error C2061 syntax error: identifier ‘PreparedStatement‘