当前位置:网站首页>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 .
边栏推荐
- Security team: Recently, there is an rce vulnerability in the COREMAIL email client of windows, which may lead to the disclosure of the private key of the wallet
- Science | 华盛顿大学利用AI和结构预测设计全新蛋白质
- ESMFold: AlphaFold2之后蛋白质结构预测的新突破
- Basic select statement
- The NFT market pattern has not changed. Can okaleido set off a new round of waves?
- Novice online interview [Hangzhou multi tester] [Hangzhou multi tester _ Wang Sir]
- Part II - C language improvement_ 12. Packaging and use of dynamic / precision Library
- Pytorch learning record (II): tensor
- np. transpose & np.expand_ dims
- 【2016】【论文笔记】差频可调谐THz技术——
猜你喜欢

np.transpose & np.expand_dims

np. transpose & np.expand_ dims

上千Tile的倾斜模型浏览提速,告别一块一块往外蹦的尴尬
The memory occupation of the computer is too high after it is turned on (more than 50%)

带你熟悉云网络的“电话簿”:DNS

Hcia-r & s self use notes (23) DHCP

Vit:vision transformer super detailed with code

Sign up now | frontier technology exploration: how to make spark stronger and more flexible

At 12:00 on July 17, 2022, the departure of love life on June 28 was basically completed, and it needs to rebound

Part II - C language improvement_ 6. Multidimensional array
随机推荐
如何使用数据管道实现测试现代化
Azure Synapse Analytics 性能优化指南(4)——使用结果集缓存优化性能
JUnit、JMockit、Mockito、PowerMockito
Signal debugging document developed by car
Three effective strategies for the transformation of data supply chain to be coordinated and successful
An online accident, I suddenly realized the essence of asynchrony
The NFT market pattern has not changed. Can okaleido set off a new round of waves?
pgsql -&gt; flink cdc -&gt; flink -&gt; Mysql, if a PgSQL CDC
[interview: concurrency 26: multithreading: two-phase termination mode] volatile version
Pytorch learning record (II): tensor
Practical project: boost search engine
Write golang simple C2 remote control based on grpc
第二部分—C语言提高篇_7. 结构体
Positioning of soaring problems caused by online MySQL CPU
How to transfer the GPX data collected by CTI RTK out of KML and SHP with attributes for subsequent management and analysis
Typescript stage learning
Pyqt5 how to set pushbutton click event to obtain file address
How to use data pipeline to realize test modernization
JSON formatting gadget -- pyqt5 instance
数据供应链的转型 协调一致走向成功的三大有效策略