当前位置:网站首页>C language array
C language array
2022-06-12 03:05:00 【kjl167】
C Language Array
Array : A collection of elements of the same type
One 、 One dimensional array
1.1 Declaration of one-dimensional array
Element type Array name [ Element number ]
explain : The number of elements is usually a constant expression ,c99 The standard supports variable length arrays , That is, the number of elements can be expressed by variables
int arr[10]; // Declare an integer array , Array has 10 Elements , Array name arr
/* Variable length array int n = 10; int arr[n]; */
1.2 Initialization of one dimensional array
initialization : Assign a value to an array when it is declared
int arr1[5] = {
1,2,3};
int arr2[5] = {
1,2,3,4,5};
int arr3[] = {
1,2,3};
char arr4[] = "abc" // Equate to arr4[] = {'a','b','c','\0'};
explain :
1. Assign a value to an array when it is declared , The number of array elements can be omitted , At this time, the number of elements is the number of initial values
int arr3[] = {
1,2,3}; // The number of elements is :3
2. If the number of initial values is less than the number of elements , The remaining array element values are initialized to 0
int arr1[5] = {
1,2,3}; // Equate to int arr1[5] = {1,2,3,0,0};
3. Can only be... When array is declared Array assignment , At other times, it can only be Array elements assignment , Cannot assign a value to an array
int arr1[5];
arr = {
1,2,3,4,5}; // error
int arr2[] = {
1,2,3};
int arr3[3];
arr3 = arr2;// error
1.3 Reference array elements
Array name [ Subscript ]
explain :
1. Array elements are accessed by subscripts
2. Array index from 0 Start , The subscript range is [0,size-1]
3.size = sizeof(arr) / sizeof(arr[0]); This formula in the function does not apply
#include <stdio.h>
// Print the value of each element of the array
int main()
{
int arr[5] = {
0 };
int size = sizeof(arr) / sizeof(arr[0]); //size Is the number of array elements
int i = 0;
for (i = 0; i < size; i++)
{
arr[i] = i; // Assign values to array elements
}
for (i = 0; i < size; i++)
{
printf("%d ",arr[i]);// Print array elements
}
return 0;
}
Output
1 2 3 4 5
1.4 One dimensional arrays are stored in memory
One dimensional arrays are stored continuously in memory , Address usage is from low address to high address
#include <stdio.h>
// 32 Bit environment test
int main()
{
int arr[5] = {
1,2,3,4,5 };
int size = sizeof(arr) / sizeof(arr[0]); //size Is the number of array elements
int i = 0;
for (i = 0; i < size; i++)
{
printf("%p\n", &arr[i]); // Print the address of the corresponding element in memory
}
return 0;
}
Output
010FFD80
010FFD84
010FFD88
010FFD8C
010FFD90

Two 、 Two dimensional array
2.1 Two dimensional array declaration
Element type Array name [ Row number ][ Number of columns ]
Number of array elements = Row number * Number of columns , The number of lines can be omitted in the declaration ( But it must be initialized )
int arr[3][2]; // Declare a two-dimensional array , Array name arr, Array has 3 That's ok 2 Column , The number of elements is 3*2, Element type is int
2.2 Initialization of 2D array
initialization : Assign values to an array when it is declared
int arr1[3][3] = {
1,2,3};
int arr2[2][2] = {
{
1},{
2,3} };
int arr3[][2] = {
{
1,2},{
3,4} };
explain :
1. The number of initial values is less than the product of rows and columns , The remaining array elements are initialized to 0
int arr1[3][3] = {
1,2,3}; // Equate to int arr1[3][3] = { {1,2,3},{0,0,0},{0,0,0} };
// Or equivalent to int arr1[3][3] = {1,2,3,0,0,0,0,0,0};
2 Can only be... When array is declared Array assignment , At other times, it can only be Array element assignment
int arr1[2][3] = {
{
1,2,3},{
4,5,6} };
int arr2[2][3];
arr2 = arr1;// error
arr2[0] = arr1[0] // error
arr2[0][0] = arr1[1][1];// correct
2.3 Reference array elements
Array name [ Line subscript ][ Column subscript ]
Line subscript : The scope is [0, Line number -1]
Column subscript : The scope is [0, Column number -1]
#include <stdio.h>
int main()
{
int arr[2][3] = {
0 };
int i = 0;
int j = 0;
int flag = 0;
for (i = 0; i < 2; i++) // Control line subscript
{
for (j = 0; j < 3; j++) // Control column subscript
{
arr[i][j] = flag; // Assign values to array elements
flag++;
}
}
for (i = 0; i < 2; i++) // Control line subscript
{
for (j = 0; j < 3; j++) // Control column subscript
{
printf("arr[%d][%d] = %d ", i, j, arr[i][j]); // Print the corresponding array element values
}
printf("\n");// After printing a row of array, it will wrap
}
return 0;
}
2.4 Two dimensional arrays are stored in memory
Two dimensional arrays are stored continuously in memory , Address usage is from low address to high address
#include <stdio.h>
int main()
{
int arr[2][3] = {
0 };
int i = 0;
int j = 0;
for (i = 0; i < 2; i++) // Control line subscript
{
for (j = 0; j < 3; j++) // Control column subscript
{
printf("&arr[%d][%d] = %p\n",i,j,&arr[i][j]);
}
}
return 0;
}
Output
&arr[0][0] = 00B8FE6C
&arr[0][1] = 00B8FE70
&arr[0][2] = 00B8FE74
&arr[1][0] = 00B8FE78
&arr[1][1] = 00B8FE7C
&arr[1][2] = 00B8FE80

3、 ... and 、 Multidimensional arrays
Multidimensional arrays : Dimension greater than 1 This is called a multidimensional array , Such as : Two dimensional array 、 Three dimensional array 、 Four bit array, etc
3.1 Multidimensional array declaration
int arr[3][4][5];// Statement 1 A three-dimensional array , Array name arr, The array is 3 row 、4 That's ok 、5 Column , Element number =3*4*5, Element type is int
3.2 Multidimensional array initialization
int arr1[2][2][2 = {
{
{
1,2},{
3,4} },{
{
5,6},{
7,8} } };
explain : In a multidimensional array , Only the first dimension can be provided by default according to the initialization list , The remaining dimensions must be written explicitly
int arr1[][2][2 = {
{
{
1,2},{
3,4} },{
{
5,6},{
7,8} } }; // The first dimension is omitted , By counting the number of subarrays , The first dimension is 2
Four 、 Array subscript out of bounds
The subscript of the array is bounded , The subscript range is [0, Element number -1], When the subscript is not in this range, the access to the legal space of the array is exceeded , That is, the array subscript is out of bounds .C The language standard does not prescribe array subscript out of bounds checking , Subscript out of bounds checking involves more overhead than expected ( It involves whether the pointer space is in the array space ), So most compilers do not do subscript out of bounds checking
4.1 Subscript cross-border access
#include <stdio.h>
int main()
{
int arr[5] = {
1,2,3,4,5 };
printf("arr[%d] = %d\n", -1, arr[-1]); // Memory space before accessing the array
printf("arr[%d] = %d\n", 5, arr[5]); // Memory space after accessing the array
return 0;
}
Output
arr[-1] = -858993460
arr[5] = -858993460
Most compilers only report warnings for cross-border access , The program can still run
4.2 Subscript out of range modification
#include <stdio.h>
int main()
{
int arr[5] = {
1,2,3,4,5 };
arr[-1] = 2; // The value stored in the memory space before modifying the array
arr[5] = 3; // The value stored in the memory space after modifying the array
return 0;
}
Program error ,Run-Time Check Failure #2 - Stack around the variable ‘arr’ was corrupted.
Conclusion : We should check whether the array subscript is out of bounds , Don't count on compilers
5、 ... and 、 Arrays and pointers
5.1 Array name
5.1.1 What is the array name
stay C in , Almost all expressions that use array names , Array name is the address of the first element of the array , It's a pointer constant
example 1
#include <stdio.h>
int main()
{
int arr[5] = {
1,2,3,4,5 };
printf("p = %p\n", arr);
printf("&arr[0] = %p\n", &arr[0]);
//arr++; This code is wrong , because arr Is the address of the first element of the array , It's a pointer constant , Constant cannot be changed
return 0;
}
Output
p = 008FFE64
&arr[0] = 008FFE64
example 2
#include <stdio.h>
int main()
{
int arr1[5] = {
1,2,3,4,5 };
int arr2[5];
arr2 = arr1;// This code is wrong , because arr2 yes arr2 The address of the first element of the array , A pointer constant , Cannot be modified
return 0;
}
5.1.2 Two exceptions to array names
Only in two cases , The array name is not the address of the first element of the array
exception 1:sizeof( Array name )
#include <stdio.h>
//32 Bit environment test
int main()
{
int arr[5] = {
1,2,3,4,5 };
/* stay sizeof Put a separate array name inside , The array name represents the size of the entire array ,int The type size is 4, The number of elements is 5, The array size is 20 byte Instead of calculating as an address size (32 The bit platform address size is 4 byte ) */
printf("%d\n", sizeof(arr));
return 0;
}
Output
20
exception 2:& Array name
#include <stdio.h>
//32 Bit environment test
int main()
{
int arr[5] = {
1,2,3,4,5 };
printf("&arr = %p\n", &arr); // & Array name , What you get is the array address
printf("&arr[0] = %p\n", &arr[0]); // &arr[0], Get the address of the first element of the array
printf("arr = %p\n", arr); // The array name represents the address of the first element , Get the address of the first element of the array
printf("---------------\n");
printf("&arr+1 = %p\n", &arr+1);
printf("&arr[0]+1 = %p\n", &arr[0]+1);
printf("arr+1 = %p\n", arr+1);
return 0;
}
Output
&arr = 004FF924
&arr[0] = 004FF924
arr = 004FF924
---------------
&arr+1 = 004FF938
&arr[0]+1 = 004FF928
arr+1 = 004FF928

5.2 Subscript references and pointer expressions
We visited ( modify ) Array elements use subscript references , But we know that the array name is usually the address of the first element of the array , It's a pointer constant , therefore In essence, subscript references are disguised as pointer expressions .
*array[subscript ] Equate to (array + subscript )
#include <stdio.h>
//32 Bit environment test
int main()
{
int arr[5] = {
1,2,3,4,5 };
int i = 0;
printf(" Print element values using subscript references \n");
for (i = 0; i < 5; i++)
{
printf("%d ", arr[i]);
}
int* p = arr; // Shaping pointer variables p Deposit arr The address of the first element of the array
printf("\n Print element values using pointer expressions \n");
for (i = 0; i < 5; i++)
{
printf("%d ", *(p+i)); // *(p+i) Equate to *(arr+i)
}
return 0;
}
Output
Print element values using subscript references
1 2 3 4 5
Print element values using pointer expressions
1 2 3 4 5
When the pointer is to the left of the expression , Modify the pointer to the value stored in the space
When the pointer is to the right of the expression , The access pointer points to the value stored in the space
#include <stdio.h>
int main()
{
int arr[5] = {
1,2,3,4,5 };
int* p = arr;
*p = 10; // The pointer is to the left of the expression , modify p Point to a space to store values , Equate to arr[0] = 10;
int i = *p; // The pointer is to the right of the expression , visit p Point to a space to store values , Equate to int i = arr[0]
printf("*p = %d\n", *p);
printf("i = %d\n", i);
printf("arr[0] = %d\n", arr[0]);
return 0;
}
Output
*p = 10
i = 10
arr[0] = 10
explain :
1. Subscript references are more readable than pointer expressions
2. Subscript references are never more efficient than pointers , But pointers are sometimes more efficient than subscript references
5.3 The difference between array and pointer
Arrays and pointers are not equal
- When declaring an array , The compiler allocates memory space for the array according to the number of elements specified in the declaration , And then create the array name , Its value is a constant , Point to the starting position of this space .
- When declaring a pointer variable , The compiler only allocates memory space for the pointer itself , If the pointer variable is a global variable, it is initialized to by default NULL, If it is a local variable, it will not be initialized , It stores a random address value

6、 ... and 、 Arrays and functions
6.1 One dimensional array parameter transfer function design
One bit array the array name is the address of the first element of the array
When using an external one-dimensional array inside a function , You need to pass this one-dimensional array into the function , We used to design it as an array
example 1:
#include <stdio.h>
//32 Bit environment test
void print1(int arr[5]) // The formal parameter is designed as an array
{
int i = 0;
for (i = 0; i < 5; i++)
{
printf("%d ", arr[i]);
}
}
int main()
{
int arr[5] = {
1,2,3,4,5 };
print1(arr);
return 0;
}
example 2 :
We found that 1 When the design , The function is dead , The number of array elements can only be 5, When the number of external array elements is not 5 When , The function needs to be modified , Some people would think of using the inside of a function sizeof(arr) / sizeof(arr[0]) Find the number of elements , This is a wrong design method
#include <stdio.h>
//32 Bit environment test
/* Incoming argument arr It's an array name , The essence is the address of the first element of the array , It's a pointer type , The formal parameter should be designed as int* p, But it can also be written as int arr[] [] The number of inner elements may not be specified , Because compilers treat them as pointers */
void print2(int arr[])
{
int i = 0;
/* arr It's a pointer ,sizeof(arr) Is to find the size of the pointer ,32 Bit pointer size is 4 byte ,64 Position as 8 byte , This machine is 32 Bit environment therefore sizeof(arr) = 4. sizeof(arr[0]) because arr[0] yes int type , therefore sizeof(arr[0]) Equate to sizeof(int) = 4. namely sizeof(arr) / sizeof(arr[0]) Equate to 4 /4 =1, namely int size = 1; */
int size = sizeof(arr) / sizeof(arr[0]);
for (i = 0; i < size; i++)
{
printf("%d ", arr[i]);
}
}
int main()
{
int arr[5] = {
1,2,3,4,5 };
print2(arr);// Incoming argument
return 0;
}
example 3:
Through example 2 We know , If you need to know the number of external array elements inside the function , You can pass an explicit parameter to a function , Indicates the number of array elements
#include <stdio.h>
//32 Bit environment test
void print3(int arr[],int size) // The formal parameter is designed as an array ,size Is the number of array elements
{
int i = 0;
for (i = 0; i < size; i++)
{
printf("%d ", arr[i]);
}
}
int main()
{
int arr[5] = {
1,2,3,4,5 };
int size = sizeof(arr) / sizeof(arr[0]);
print3(arr,size);
return 0;
}
example 4
We know that the array name of a one-dimensional array is the address of the first element of the array , So we should use pointer type when designing function parameters
#include <stdio.h>
//32 Bit environment test
void print4(int* p,int size) // The form parameter is designed as a pointer
{
int i = 0;
for (i = 0; i < size; i++)
{
printf("%d ", *(p+i));
}
}
int main()
{
int arr[5] = {
1,2,3,4,5 };
int size = sizeof(arr) / sizeof(arr[0]);
print4(arr,size);
return 0;
}
Conclusion :
1. One dimensional array passes the address of the first element of the array , The essence is the pointer
2. We recommend an example 3、 example 4 Function design in the way of , In particular 4
6.2 Two dimensional array parameter transfer function design
The array name of a two-dimensional array is the address of the first element , The first element is a one-dimensional array , Array pointer
int arr[3][4];
int (*p)[4] = arr; //p Store array arr First element address
// The subscript reference operator takes precedence over the indirect access operator , But because of the parentheses ,p First and foremost * matching , namely p Is a pointer . Next with
// Subscript reference operators match , indicate p Point to an array of some type , Finally and int matching , therefore p Is a pointer to an array , Array has 10 individual
// Elements , Each element is int type
When using an external two-dimensional array inside a function , You need to pass the two-dimensional array into the function , We used to design it as an array
example 1:
#include <stdio.h>
//32 Bit environment test
void print1(int arr[2][2]) // Array form
{
int i = 0;
int j = 0;
for (i = 0; i < 2; i++)
{
for (j = 0; j < 2; j++)
{
printf("arr[%d][%d] = %d ", i, j, arr[i][j]);
}
printf("\n");
}
}
int main()
{
int arr[2][2] = {
{
1,2},{
3,4} };
print1(arr);
return 0;
}
example 2:
We found that 1 When the design , The function is dead , The rows and columns of an array can only be 2, In other cases, the function needs to be modified . It can be done by 2 An explicit parameter is passed to the function , Indicate rows and columns
#include <stdio.h>
//32 Bit environment test
/* The array name of a two-dimensional array is the address of a one-dimensional array , Essence is a pointer , Use array form to pass parameters , The size of the column cannot be omitted , This can only be written to death */
void print2(int arr[][2],int row,int col) // Array form
{
int i = 0;
int j = 0;
for (i = 0; i < row; i++)
{
for (j = 0; j < col; j++)
{
printf("arr[%d][%d] = %d ", i, j, arr[i][j]);
}
printf("\n");
}
}
int main()
{
int arr[2][2] = {
{
1,2},{
3,4} };
int row = sizeof(arr) / sizeof(arr[0]); // Calculate trip
int col = sizeof(arr[0]) / sizeof(arr[0][0]); // Calculate the column
print2(arr,row,col);
return 0;
}
example 3
We know that the array name of a two-dimensional array is the address of the first element of the array , namely 1 The address of a one-dimensional array , So we should use pointer type when designing function parameters
#include <stdio.h>
//32 Bit environment test
void print2(int (*p)[2], int row, int col) // Pointer form
{
int i = 0;
int j = 0;
for (i = 0; i < row; i++)
{
for (j = 0; j < col; j++)
{
printf("arr[%d][%d] = %d ", i, j, *(*(p+i)+j));
}
printf("\n");
}
}
int main()
{
int arr[2][2] = {
{
1,2},{
3,4} };
int row = sizeof(arr) / sizeof(arr[0]); // Calculate trip
int col = sizeof(arr[0]) / sizeof(arr[0][0]); // Calculate the column
print2(arr,row,col);
return 0;
}
边栏推荐
- What is the core of Web3?
- Paper recommendation: relicv2, can the new self supervised learning surpass supervised learning on RESNET?
- 2020-12-17
- Wechat applet project example - Fitness calculator
- What is the difference between the gin framework of golang and the various methods of receiving parameters and various bindings?
- [digital signal processing] correlation function (power signal | cross correlation function of power signal | autocorrelation function of power signal)
- Quelles sont les solutions dans tous les domaines?
- Unity3d ugui translucent or linear gradient pictures display abnormally (blurred) problem solving (color space mismatch)
- Depth copy
- 2020-12-06
猜你喜欢

Apache simple honeypot

Demand and business model innovation - demand 8- interview

How to make div 100% page (not screen) height- How to make a div 100% of page (not screen) height?

I2C protocol overview

Application of ankery anti shake electric products in a chemical project in Hebei

Recommend 6 office software, easy to use and free, double the efficiency

maya前台渲染插件mel脚本工具

In 2022, don't you know the difference between arrow function and ordinary function?

errno: -4091, syscall: ‘listen‘, address: ‘::‘, port: 8000

Paper recommendation: relicv2, can the new self supervised learning surpass supervised learning on RESNET?
随机推荐
推荐6款办公软件,好用还免费,效率翻倍
I2C协议概述
Drawcall, batches, setpasscall in unity3d
WPS table learning notes - highlight duplicate values
Selection (045) - what is the output of the following code?
ssh公钥登录失败报错:sign_and_send_pubkey: no mutual signature supported
Introduce the functions of the new project aleo
Comparison of scores
无限循环判断方法;
cupp字典生成工具(同类工具还有crunch)
A single quarter of educational technology revenue of 230million: a year-on-year decrease of 51% and a sharp narrowing of net loss
ARD3M电动机保护器在煤炭行业中的应用
2020-12-12
[DFS "want" or "don't"] seek subsets; Seeking combination
Addition and multiplication of large integers;
TCP three handshakes and four waves
Laravel 8 selects JWT for interface verification
Maya Front Office Rendering plug - in Mel script Tool
函数模板 Function Templates
跨域有哪些解决方法?