当前位置:网站首页>C language array
C language array
2022-07-26 23:39:00 【Ants look up to the sky】
List of articles
Preface
An array is a collection of elements of the same type , In the learning process , One dimensional array and two-dimensional array are the most commonly used .
One dimensional array creation and initialization
One dimensional array creation
The way one-dimensional arrays are created :
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 the array
The following is an example of array creation :
// Code 1
int arr1[10];
// Code 2,** This method may cause errors in some compilers , But actually C Language allows you to specify the size of an array with variables **
int count=10;
int arr2[count];
// Code 3
char arr3[10];
float arr4[5]
double arr5[20];
Initialization of one dimensional array
The initialization of an array refers to , Created in array meanwhile Give the array some reasonable initial values .
Examples are as follows :
int arr1[10] = {
1,2,3};
int arr2[] = {
1,2,3,4};
int arr3[5] = {
1,2,3,4,5};
char arr4[3] = {
'a',98,'c'};
char arr5[] = {
'a','b','c'};
char arr6[] = "abcdef" ;
If the number of array elements is not specified when creating an array , Then the number of elements of the array is determined according to the initialization content .
The use of one-dimensional arrays
For the use of arrays, we introduced an operator [] The subscript reference operator is actually the operator of array access .
The code example is as follows :
#include <stdio.h>
int main()
{
int arr[10]={
0};// Incomplete initialization of arrays
int sz=sizeof(arr)/sizeof(arr[0]);// Count the number of elements in an array
int i=0;// Do array subscripts , Array subscript is from 0 Start
for(i=0;i<10;i++)
{
arr[i]=i;// Array assignment
}
for(i=0;i<10;i++)
{
printf("%d ",arr[i]);// Output array contents
}
return 0;
}
The code executes as follows :
summary ;1. Arrays are accessed using subscripts , The subscript is from 0 At the beginning .
2. The number of array elements can be calculated .
3. If the array is not initialized or assigned , Then garbage values may be stored in the array , It may also store 0, This stored result will be determined by the compiler .
One dimensional array storage in memory
Let's tap the code to observe the storage of one-dimensional arrays in memory ( Just find out here , You don't have to go into it , In the future, the study of pointer will be explained in detail )
#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]);// Print the address of each element of the array in memory
//%p Is the address type
}
return 0;
}

Pictured above , You can see the address of each element , This involves the binary problem , I suggest you know about various decimal conversions , It is helpful for future study .
As can be seen from the figure above , The address of each element of the array is adjacent , It can be concluded that : Arrays are continuously stored in memory .
The creation and initialization of two-dimensional array
The creation of two-dimensional array
In fact, a two-dimensional array is a matrix in Mathematics , The code is shown as follows :
int arr[3][4];//**3 That's ok 4 Two dimensional array of columns ( matrix )**
char arr[3][5];//**3 That's ok 5 Two dimensional array of columns ( matrix )**
double arr[2][4];//**2 That's ok 4 Two dimensional array of columns ( matrix )**
Initialization of 2D array
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 **
The use of two-dimensional arrays
#include <stdio.h>
int main()
{
int arr[3][4] = {
0 };//** Two dimensional arrays are not fully initialized **
int i = 0;
for (i = 0; i < 3; i++)
{
int j = 0;
for (j = 0; j < 4; j++)
{
arr[i][j] = i * 4 + j;//** Assign a value to a two-dimensional array **
}
}
for (i = 0; i < 3; i++)
{
int j = 0;
for (j = 0; j < 4; j++)
{
printf("%d ", arr[i][j]);//** Output the elements of a two-dimensional array **
}
printf("\n");
}
return 0;
}

The picture above shows 3 That's ok 4 Two dimensional array of columns ( matrix ).
Two dimensional array storage in memory
Here we try to print the address of each element of the 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;
}

Here, because it's just a print address , So there is no assignment to the two-dimensional array , Because when creating a two-dimensional array , Memory has been opened up . It can be seen from the above that the addresses of two-dimensional array elements are also continuous in memory .
An array
The subscript of an array is range limited .
The subscript of the array is specified 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
That's right. ,
So when programmers write code , You'd better do cross-border inspection yourself .
The following is a code example :
#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;
}

Pictured above , The last string of numbers is usually called garbage value .
Arrays as function arguments
First, let's look at a set of code :
#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);// For the time being, let's understand * Is the value operator , It will be explained later when learning pointer
// Output results
return 0;
}

From the picture above, we can get , Array name is the address of the first element of the array , But there are two exceptions :
int arr[10] = {
0};
printf("%d\n", sizeof(arr));
The print out here is 40, So we can conclude that :
1.sizeof( Array name ) Will calculate the size of the entire array ,sizeof Put a separate array name inside , The array name represents the entire array .
2.& Array name , What we get is the address of the array ,& Array name , The array name represents the entire array .
In addition to the above two cases , All array names represent the address of the first element of the array .
We will take bubble sorting as an example , Here we first have a brief introduction , In the follow-up study of data structures and algorithms, we will explain in depth ,
As shown in the figure , Bubble sort is to sort an array in ascending or descending order , Every time I compare two , Compare until the last element of the array , If the array has n Elements can be compared at most n-1 Trip to , The following is a code example :
#include <stdio.h>
void bubble_sort(int arr[], int sz)
{
int i = 0;// Number of bubbling sortings
for (i = 0; i < sz-1; i++)
{
// Bubble sort
int j = 0;
for (j = 0; j < sz-1-i; j++)
{
if (arr[j] > arr[j + 1])
{
int tmp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = tmp;
}
}
}
}
int main()
{
int arr[10] = {
1,3,5,7,9,2,4,6,8,0};
int sz = sizeof(arr) / sizeof(arr[0]);// Count the number of array elements
bubble_sort(arr, sz);// Passing an array as a parameter to a function requires only the array name
int i = 0;
for (i = 0; i < sz; i++)
{
printf("%d ", arr[i]);
}
return 0;
}

When passing an array as shown in the above figure , Just pass in the array name , If Chuan arr[0] It means that the first element of the array is passed in instead of the entire array .
Add here , stay main The array created in function has no way to calculate the number of array elements and array size in other functions , So when taking an array as a function parameter , The number of array elements should also be transferred to the function .
The final production is not easy , Looking forward to your three consecutive and attention , You are welcome to write a private letter or point out what needs to be corrected in the comment area .
边栏推荐
- Distributed lock and its implementation
- Custom type
- [shader realizes swaying effect _shader effect Chapter 4]
- Real time voice quality monitoring
- Three effective strategies for the transformation of data supply chain to be coordinated and successful
- Signal debugging document developed by car
- 华裔科学家Ashe教授对涉嫌造假的Nature论文的正面回应
- [Luogu] p2341 popular cattle
- 力扣152题:乘积最大子数组
- In simple terms, cchart's daily lesson - Lesson 59 of happy high school 4 comes to the same end by different ways, and the C code style of the colorful interface library
猜你喜欢

Vector execution engine framework gluten announced the official open source and appeared at spark technology summit

HCIA-R&S自用笔记(18)园区网架构基础、交换机工作原理、VLAN原理

公有云安全性和合规性方面的考虑事项

第二部分—C语言提高篇_11. 预处理

Part II - C language improvement_ 6. Multidimensional array

Problems and solutions encountered in using nextline(), nextint() and next() in scanner

1. Configuration environment and project creation

Hcia-r & s self use notes (21) STP technical background, STP foundation and data package structure, STP election rules and cases

Real time voice quality monitoring
![[2016] [paper notes] differential frequency tunable THz technology——](/img/7e/71126950250997fc436a4ee730aee7.png)
[2016] [paper notes] differential frequency tunable THz technology——
随机推荐
MySQL syntax uses detailed code version
Dajiang Zhitu and CC have produced multiple copies of data. How to combine them into one and load them in the new earth map
29、 Implementation of xv6 file system (GDB tracks mkfs, buffer cache and log)
What is Base64?
About statefulwidget, you have to know the principle and main points!
18、打开、保存文件对话框使用小记
P5469 [noi2019] robot (Lagrange interpolation, interval DP)
Thousands of tiles' tilt model browsing speeds up, saying goodbye to the embarrassment of jumping out one by one
Several inventory terms often used in communication
Part II - C language improvement_ 5. Bit operation
Use Arthas to locate online problems
Pytorch learning record (II): tensor
Vit:vision transformer super detailed with code
第二部分—C语言提高篇_9. 链表
告别宽表,用 DQL 成就新一代 BI
Too busy with scientific research to take care of your family? Chen Ting: life cannot have only one fulcrum
Tensorflow2.0 深度学习运行代码简单教程
SQL Basics
[postgresql]postgresqlg use generate_ Series() function completes statistics
Three person management of system design