当前位置:网站首页>C language explanation series - array explanation, one-dimensional array, two-dimensional array
C language explanation series - array explanation, one-dimensional array, two-dimensional array
2022-07-28 07:39:00 【Sad pig, little pig】
One dimensional array
One dimensional array creation
We said , Array Is a collection of elements of the same type , So how to create an array ?
type_t arr_name [const_n]
type_t : The type of array element
const_n: Is a constant expression , Used to specify the size of an array
arr_name: It's an array name
We demonstrate how to create an array in the code
int main()
{
int arr[3] = {
1,2,3 };
int i = 0;
int sz = sizeof(arr)/sizeof(arr[0]);
for (i = 0; i < sz; i++)
{
printf("%d ", arr[i]);
}
return 0;
}
This line of code int arr[3] = { 1,2,3 };· It realizes the creation of an integer array with three elements , Then we go through the cycle , Traversed the array elements , Get the three elements stored in the array . So we are creating arrays , stay [] Can variables be used inside ?
We create a variable n take 3 Assigned to him , And use this variable to create an array , We found that the compiler prompted us Expected constant expression , Because of the creation of arrays , stay C99 Before standard ,[] Use a constant in , stay C99 The standard supports Variable length array The concept of , The size of the array can be specified by variables , But arrays cannot be initialized .
Variable length array
It's not that the length of the array can be changed arbitrarily , But before the array is created, the length of the array can be changed according to the user's input and needs . When the array is created , The length cannot be changed .
Initialization of an array
Array initialization refers to , While creating the array, give the contents of the array some reasonable initial values .
int main()
{
int arr[10] = {
1};
}
By debugging we found that , We initialize the first element in the array to 1, be left over 9 Elements , The compiler is initialized to 0, We call this initialization Incomplete initialization . There are also many initialization methods, such as :int arr[] = {1,2,3,4} This does not specify the size of the array , The size of the array is determined by the initialization contents .
It's worth noting that
int main()
{
char arr1[] = "abc";
char arr2[] = {
'a','b','c' };
printf("%d\n",sizeof(arr1));
printf("%d\n", sizeof(arr2));
}
We found that the initialization in the array is also given abc Why is the length of the array different for three characters ? as a result of char arr1[] = "abc"; When initializing the array like this "abc" Such a string has an end flag \0, It is also initialized as the element of the array .
The use of one-dimensional arrays
For the use of arrays, we can use [], Subscript reference operator . We can use it to traverse the array , Realize some functions we need .
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;
for (i = 0; i < 10; i++)
{
arr[i] = i;
}
// Output the contents of the array
for (i = 0; i < 10; ++i)
{
printf("%d ", arr[i]);
}
return 0;
}
We can calculate the length of the array , Traversing the output array , Get any element in the array .
When using arrays, we need to pay attention to
1. Arrays are accessed using subscripts , The subscript is from 0 At the beginning .
2. The size of the array can be calculated
Storage of one-dimensional array in memory
int main()
{
int arr[10] = {
1,2,3,4,5,6,7,8,9,10 };
int sz = sizeof(arr) / sizeof(arr[0]);
int i = 0;
for (i = 0; i < sz; i++)
{
printf("arr[%d] = %p\n", i, &arr[i]);
}
return 0;
}
We get the address of each element in the array through the code , Through observation we found that , The address of the array element , As the subscript of the array element increases , We come to a conclusion Arrays are stored continuously in memory . As the array subscript grows , The address also changes from low to high .
Two dimensional array
The creation of two-dimensional array
The creation of a two-dimensional array is essentially similar to the creation of a one-dimensional array , Just because it is a two-dimensional array, there is a concept of rows
int main()
{
int arr[2][3] = {
0 };
}
So we create a 2 That's ok 3 Two dimensional array of columns .
Initialization of 2D array
In fact, the initialization of two-dimensional array , The essence of one-dimensional array is the same , We just need to treat the code on each line as a one-dimensional array .
int main()
{
int arr[3][4] = {
1,2,3,4,5 };
int arr[3][4] = {
{
1, 2, 3}, {
4,5 }};
int arr[][4] = {
{
2,3},{
4,5} };// If the two-dimensional array is initialized , Lines can be omitted , Columns cannot be omitted
}
As shown in the code above , We can initialize the two-dimensional array , stay {} Medium {} Used to distinguish each line , There is also something to pay attention to In a two-dimensional array , If you initialize , Lines can be omitted , But columns cannot be initialized .
The use of two-dimensional arrays
Same as one-dimensional array , By using [] How to get subscripts , Look at the code
int main()
{
int i = 0;
int arr[2][2] = {
0};
for (i = 0; i < 2; i++)
{
int j = 0;
for (j = 0; j < 2; j++)
{
scanf("%d", &arr[i][j]);
}
}
for (i = 0; i < 2; i++)
{
int j = 0;
for (j = 0; j < 2; j++)
{
printf("%d", arr[i][j]);
}
}
}
So let's create one first 2 That's ok 2 Two dimensional array of columns , Then traverse the array for assignment , Traverse the array output again . Is it roughly the same as one-dimensional array .
Two dimensional array storage in memory
We say that two-dimensional arrays are being created 、 initialization 、 The use and other aspects are very similar to one-dimensional arrays , But one is a one-dimensional array and the other is a two-dimensional array , It should be different in storage , Is this the case ? We look for the answer in the code :
int main()
{
int arr[3][4] = {
0 };
int i = 0;
int j = 0;
for (i = 0; i < 3; i++)
{
for (j = 0; j < 4; j++)
{
printf("arr[%d][%d] = %p\n", i, j, &arr[i][j]);
}
}
return 0;
}
We iterate through the array , Print the address of each element in the two-dimensional array , In fact, two-dimensional arrays are also stored continuously in memory . The last element of each line is adjacent to the address of the first element in the next line , The address also increases as the subscript of the array element increases , So it looks like , The storage method in memory is the same as that of one-dimensional array .
Out of bounds access to arrays
The subscript of an array is range limited , The subscript of the array stipulates , from 0 Start , If there is n Elements , So the subscript of the last element is n-1.
If our subscript is less than 0 Or greater than n-1, Then it is the cross-border access of the array , Access beyond the legal space of the array .
for example :
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", arr[i]);
}
return 0;
}
When i = 10 When we say , Cross border visit , Two dimensional arrays have the same boundary crossing problem as one-dimensional arrays .
Arrays as function arguments
Bubble sort
void bubble_sort(int arr[])
{
int i = 0;
int sz = sizeof(arr) / sizeof(arr[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[] = {
10,9,8,7,6,5,4,3,2,1 };
int i = 0;
bubble_sort(arr);
for (i = 0; i < sizeof(arr)/sizeof(arr[0]); i++)
{
printf("%d ", arr[i]);
}
return 0;
}
We use bubble sort to achieve ascending sort , The principle is to put the elements in the array , Compare with his adjacent elements in turn , If the front element is larger than the rear element adjacent to it , Then let these two elements Exchange , Put the element with large value backward , In turn , To meet our needs . We perform our code discovery
Only the first two elements are exchanged , After that, the elements have not changed. Why ? Through debugging, we found that
There should have been 10 Array of elements , The length of the array calculated by calculation is 2, Why is that ? It turns out that when array elements are used as parameters , Pass is the first address of the array , Instead of the entire array . So the essence of the array name is actually the first address of the array .
notes :
- 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 .
So we make changes to the code , We calculate the array length in the main function , Pass to the user-defined function to use , We can solve our problems .
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[] = {
10,9,8,7,6,5,4,3,2,1 };
int i = 0;
int sz = sizeof(arr) / sizeof(arr[0]);
bubble_sort(arr,sz);
for (i = 0; i < sizeof(arr)/sizeof(arr[0]); i++)
{
printf("%d ", arr[i]);
}
return 0;
}
In this way, we realize our needs , Well, the above is some knowledge about arrays .
边栏推荐
- Modify the conf file through sed
- Student duty problems
- EMC设计攻略 —时钟
- 动态内存管理知识点
- The "nuclear bomb level" log4j vulnerability is still widespread and has a continuing impact
- RFID辐射测试小结
- LeNet5、AlexNet、VGGNet、ResNet
- The first common node of two linked lists -- two questions per day
- 深入剖析单例模式的实现
- JS secondary linkage Department
猜你喜欢

5G 商用第三年:无人驾驶的“上山”与“下海”

ArcGIS JS自定义Accessor,并通过watchUtils相关方法watch属性

华为交换机拆解,学EMC基本操作

Summary of project experience

Redis的RDB持久化和AOF持久化的底层原理

动态内存管理知识点

Collection | combined with my personal experience, I have summarized these seven EMC related knowledge

.NET 6.0中使用Identity框架实现JWT身份认证与授权

EMC整改思路

Near infrared two region agzs quantum dots wrapped deoxyribonucleic acid dna|dna agzsqds (Qiyue)
随机推荐
Merge two sorted linked lists - two questions per day
Dry goods | share an EMC actual case and rectification process
[shaders realize negative anti color effect _shader effect Chapter 11]
磁环选型攻略及EMC整改技巧
Summary of project experience
Collector原理解析
指针进阶练习
The cornerstone of EMC - complete knowledge of electromagnetic compatibility filtering!
Matplotlib绘图笔记基础直线、折线、曲线
软考证书还能这样用!拿到证书=获得职称?
DNA modified rhodium RH nanoparticles rhnps DNA (DNA modified noble metal nanoparticles)
xmpp 服务研究(二) prosody 创建账户
4.1.4 why set the member variable to private
“核弹级” Log4j 漏洞仍普遍存在,并造成持续影响
Earliest deadline first (EDF)
EMC中class A和class B哪个更严格?
MySQL view the memory size of a table
EMC设计攻略 —时钟
Deeply analyze the implementation of singleton mode
通过sed 修改conf文件