当前位置:网站首页>C language layered understanding (C language array)
C language layered understanding (C language array)
2022-07-27 14:29:00 【Playful green axis】
List of articles
- 1. One dimensional array creation and initialization
- 2. The use of one-dimensional arrays
- 3. One dimensional array storage in memory
- 4. The creation and initialization of two-dimensional array
- 5. The use of two-dimensional arrays
- 6. Two dimensional array storage in memory
- 7. Array bounds problem
- 8. Array as a function parameter
1. One dimensional array creation and initialization
First , We need to know that an array is a collection of elements of the same type .
1.1 One dimensional array creation
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
The problems we encountered when creating
1. Array [] Can it be a variable in
This is visual studio 2022 Situation in :
stay visual studio 2022 We can't see it in , In fact, arrays [ Variable ] This grammar is c99 Standard , It is called variable length array . Obviously ,visual studio 2022 I won't support it c99 edition .
In support of c99 It can run under the standard compiler , No errors are reported .
2. Can I create an array without specifying the size of the array

That's not gonna work , You must specify the space size when creating ., Otherwise, it will report a mistake .
3. If the array space is too large, the stack area will be full

4. Add
int arr[2+3]// This grammar is right ,[] It can be an expression
char arr1[2 + 3];
int arr2[2 + 3];
int arr3[3 + 2];// Addition supports commutative law
float arr4[4 + 3];
double arr5[5 + 3];
// All the above are correct , Don't question
Be careful : Array creation , stay C99 Before standard , [] You have to give a constant in the , You can't use variables . stay C99 The standard supports the concept of variable length arrays , The size of the array can be specified by variables , however Array cannot be initialized
1.2 Initialization of one dimensional array
First, understand the meaning of initialization and assignment :
int a = 0;// This is called initialization
int n;
n = 20;// This is called assignment
Initialization is to give a value while creating a variable .
Assignment is to assign a value to a variable after it is created
The emphasis is on initialization at the same time , Assignment is carried out one after another
List the common problems of one-dimensional array initialization
1. int arr[] = {1,2,3} Is the writing OK ?
This kind of writing is OK .
arr What's in the array is 123, There is no given space size , The size of the array is automatically given according to the number of elements . The space size of this array is 12.
2. int arr[10] = {1,2,3,4,5} Is the writing OK ?
There is no problem with this way of writing , This is called incomplete initialization .
What is stored in this array is 1234500000, It indicates that the initialization is incomplete , The compiler automatically initializes it as 0, The size of the array space here is 40, The reason is that we specify the size of the array .
3. have a look char arr1[] = "abc" and char arr2[] = {‘a’,‘b’,‘c’} The difference between

Here we find ,arr1 There are four elements in ,arr2 There are three elements in , explain arr1 The size of the space is 4,arr2 The size of the space is 3.
After understanding this point, let's take a look char arr3[10] = "abc" and char arr4[10] = {‘a’,‘b’,‘c’} The difference between :
What we see here is the same , It's not , We have verified above char arr1[] = “abc”,arr1 It contains a,b,c,\0,arr2 Contained in the a,b,c, Here, though arr3 and arr4 It looks the same , But it's different ,arr3 In fact, it is a,b,c,\0,0,0,0,0,0,0,arr4 In fact, it is a,b,c,0,0,0,0,0,0,0, This can explain why it is different .
2. The use of one-dimensional arrays
We know about the use of arrays [] Is a subscript reference operator , In fact, it is the operator of array access . We mentioned a concept of commutative law before , Such as :2+3 It can be written. 3+2, The two operands of a binocular operator can be exchanged , Two operands in the array In some scenes It can also be exchanged , Such as :
#include <stdio.h>
int main()
{
int arr[] = {
1,2,3,4,5 };
int i = 0;
for (i = 0; i < 5; i++)
{
printf("%d ", i[arr]);
//printf("%d ",arr[i]);
}
return 0;
}
summary :
1. Arrays are accessed using subscripts , The subscript is from 0 At the beginning .
2. The size of the array can be calculated
int arr[10];
int sz = sizeof(arr)/sizeof(arr[0]);
3. One dimensional array storage in memory
Or look at the phenomenon first and then the essence ;
Through this code, we find that the addresses are separated 4 The size of bytes , It shows that one-dimensional arrays are stored continuously in memory . As the array subscript grows , The address also changes from low address to high address .
4. The creation and initialization of two-dimensional array
4.1 The creation of two-dimensional array
int arr[3][4];// An array of three rows and four columns
char arr[3][4];
double arr[2][4];
Previous [] The number in represents the number of rows , After a [] The number in represents the number of columns .
4.2 Initialization of 2D array
4.2.1 int arr[3][4] = { 1,2,3,4 } Number storage in writing

explain : This array is an array of three rows and four columns , So the first line stores 1234, The other two lines are initialized as 0.
4.2.2 int arr[3][4] = { {1,2},{4,5}} Number storage in writing

Pictured , Find out {1,2} and {4,5} It's like a one-dimensional array , If the number of columns is insufficient, the default initialization is 0.
4.2.3 arr[][] and arr[][2] and arr[2][] Comparison
int arr[][] = {
0};// error
int arr[][2] = {
0};// correct
int arr[2][] = {
0};// error
int arr[2][2] = {
0};// correct
arr[][] and arr[2][] All will report wrong. , explain arr Missing subscript .
Be careful : If the two-dimensional array is initialized , Lines can be omitted , Columns cannot be omitted .
5. The use of two-dimensional arrays
Two dimensional arrays are also used by subscripts .
#include <stdio.h>
int main()
{
int arr[3][4] = {
{
1,2,3,4},{
5,6,7,8},{
9,10,11,12} };
int i = 0;
for (i = 0; i < 3; i++)
{
int j = 0;
for (j = 0; j < 4; j++)
{
printf("%d ", arr[i][j]);
}
printf("\n");
}
return 0;
}
6. Two dimensional array storage in memory
Look at the essence of the phenomenon :
Through observation , In fact, two-dimensional arrays are also stored continuously in memory .
7. Array bounds problem
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
That's right. , So when programmers write code , You'd better do cross-border inspection yourself
Look at the phenomenon through the code :
This is an out of bounds access in a one-dimensional array , No subscript is 10 This element of , So I don't know which piece of memory data is printed out .
Just like this ;
8. Array as a function parameter
8.1 Bubble sorting as an example
Here we take bubble sorting as an example
What is bubble sorting ?
It's easy to think of bubbles when you hear bubbles , In the water, there is a bottom floating on the water , It's getting bigger . Bubble sort here means ascending order from small to large
How to do that ?
The core is to compare two adjacent elements
Ideas :
Number of completed trips = The total number of elements -1, The number of times to complete a trip = Number of completed trips -i(i=0~( Number of completed trips -1))
Code implementation :
// Wrong code
#include <stdio.h>
void bubble_sort(int arr[])
{
int sz = sizeof(arr) / sizeof(arr[0]);
// Complete a sequence of numbers
int i = 0;
for (i = 0; i < sz-1; i++)
{
// The number of times required for a trip
int j = 0;
for (j = 0; j < sz - 1 - i; j++)
{
if (arr[j] > arr[j + 1])
{
int temp = 0;
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
int main()
{
// Give a few numbers , With 9 8 7 6 5 4 3 2 1 0 For example
int arr[10] = {
9,8,7,6,5,4,3,2,1,0 };
// Implement a function to sort
bubble_sort(arr);
// Print
int z = 0;
for (z = 0; z < 10; z++)
{
printf("%d ", arr[z]);
}
return 0;
}
Output results :
So what's wrong ?
int sz = sizeof(arr)/sizeof(arr[0]); It's wrong here , Should not be placed in a function , Because the array passes the address of the first element ( It's a pointer ), stay x86 Under the platform ,sizeof(arr)=4, stay x64 Under the platform sizeof(arr)=8, therefore sz=1, Just exchange once , So print out 8 9 7 6 5 4 3 2 1 0 Result .
The following is the correct code presentation :
// The right code
#include <stdio.h>
void bubble_sort(int arr[], int sz)
{
// Complete a sequence of numbers
int i = 0;
for (i = 0; i < sz-1; i++)
{
// The number of times required for a trip
int j = 0;
for (j = 0; j < sz - 1 - i; j++)
{
if (arr[j] > arr[j + 1])
{
int temp = 0;
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
int main()
{
// Give a few numbers , With 9 8 7 6 5 4 3 2 1 0 For example
int arr[10] = {
9,8,7,6,5,4,3,2,1,0 };
int sz = sizeof(arr) / sizeof(arr[0]);
// Implement a function to sort
bubble_sort(arr,sz);
// Print
int z = 0;
for (z = 0; z < 10; z++)
{
printf("%d ", arr[z]);
}
return 0;
}
8.2 What is the array name ?
Generally, the array name is the address of the first element .
So you certainly don't understand , Look at the picture :
All at once you understand , The first element is the first element address .
If this doesn't mean anything , Let's take another example :
The element pointed to by the array name is the same as the address taken by each element .
We say that the array name is a pointer , Let's explain :
There are two exceptions to array names ( Not all array names are first element addresses )
1.sizeof( Array name ), The array name here is the whole array , It calculates the size of the entire array , Unit is byte
prove :
2.& In array name , The array name is the size of the entire array , Fetch the address of the entire array
prove :
See bloggers' efforts to pay attention to bloggers , A little bit of praise , Support and support ! Look at the poor blogger !
Well written ,
Haha, just kidding , I hope you will support me more , Point one or two , Thank you thank you !
边栏推荐
- HDU4565 So Easy! [matrix multiplication] [derivation]
- 在Oracle VirtualBox中导入Kali Linux官方制作的虚拟机
- Ten thousand words detailed Google play online application standard package format AAB
- Database storage series (1) column storage
- Group division and characteristic analysis of depression patients based on online consultation records
- Carla notes (04) - client and world (create client, connect world, batch object, set weather, set lights, world snapshots)
- How to return to the parent directory with commands
- [luogu_p5431] [template] multiplicative inverse 2 [number theory]
- How to view revenue and expenditure by bookkeeping software
- 文旅数藏 | 用艺术的方式游云南
猜你喜欢

A Keypoint-based Global Association Network for Lane Detection
How to solve cache avalanche, breakdown and penetration problems

【论文精读】Grounded Language-Image Pre-training(GLIP)

Schematic diagram of C measuring tool

Understand JS execution context in an article

Unity3d learning note 10 - texture array

windows10 安装Sql Server 2019

Cognition -- classic of the road to success of hardware engineers
Database storage series (1) column storage

this指向问题,闭包以及递归
随机推荐
Interview eight part essay · TCP protocol
[related contents of multithreading]
Airport cloud business sign analysis
[luogu_p5431] [template] multiplicative inverse 2 [number theory]
[training day3] section [greed] [two points]
West test Shenzhen Stock Exchange listing: annual revenue of 240million, fund-raising of 900million, market value of 4.7 billion
Cognition -- classic of the road to success of hardware engineers
windows10 安装Sql Server 2019
第3章业务功能开发(添加线索备注,自动刷新添加内容)
【论文精读】Grounded Language-Image Pre-training(GLIP)
How to view revenue and expenditure by bookkeeping software
How to return to the parent directory with commands
Zhishang technology IPO meeting: annual revenue of 600million, book value of accounts receivable of 270Million
Windows10 installing SQL Server 2019
[idea] set to extract serialVersionUID
Database storage series (1) column storage
SLAM综述阅读笔记四:A Survey on Deep Learning for Localization and Mapping: Towards the Age of Spatial 2020
文献翻译__基于自适应全变差L1正则化的椒盐图像去噪
基于企业知识图谱的企业关联关系挖掘
codeforces 1708E - DFS Trees