Elementary C Language|Array

1. Creation and initialization of one-dimensional array

1.1 Array creation

数组创建方式:
type_t arr_name [const_n];
//type_t是指数组的元素类型
//const_n是一个常量表达式,用来指定数组的大小
数组创建实例:
int arr1[10];
char arr2[10];
float arr4[1];
double arr5[20];

Pay attention to a way of writing:

int count = 10;
int arr[count];

This way of writing can be written in the C99 standard. The C99 standard supports the concept of variable-length arrays. The size variable of the array can be specified, but the array cannot be initialized. For example: This way of writing is supported in the gcc compilation environment
, but it is not supported on some advanced compilers such as our vs2013, vs2019, vs2022, and a constant must be given in [].

1.2 Array initialization

When creating an array, give some reasonable initial values ​​(initialization) to the contents of the array,
for example:

int arr[10]={
    
    1,2,3};// 不完全初始化,剩余空间的大小全都会默认初始化为0
int arr2[]={
    
    1,2,3};//不给定数组的大小,由初始化的元素个数来确定数组的大小,此时的数组大小为3
int arr3[5]={
    
    1,2,3,4,5};//完全初始化
char arr4[]={
    
    'a','b','c'};
char arr5[]="abcdef";//以字符串形式初始化数组,字符串后面默认有一个'\0'

1.3 Use of one-dimensional arrays

1. The array is accessed using subscripts, which start from 0.
2. The size of the array can be obtained by calculation

Look at the code:

#include <stdio.h>
int main()
{
    
    
   int arr[10]={
    
    0};//数组的不完全初始化,只给第一个元素初始化为0,剩余空间默认初始化为0
   //计算数组的元素个数
   int sz=sizeof(arr)/sizeof(arr[0]);
   //数组元素的访问
   int i=0;//作下标
   for(i=0;i<sz;i++)
   {
    
    
     arr[i]=i;
   }
   //输出数组的内容
   for(i=0; i<sz; i++)
   {
    
    
      printf("%d",arr[i]);
   }
   return 0;
}
   

1.4 Storage of one-dimensional arrays in memory

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]);
	}
	return 0;
}

The printed result is:
insert image description here
It can be seen that with the increase of the array subscript, the address of the element increases regularly in the memory. It
can be concluded that the array is stored continuously in the memory.

Second, the creation and initialization of two-dimensional arrays

2.1 Creation of two-dimensional array

Several forms of two-dimensional array creation:

int arr[3][4];
int arr1[2][5];
char arr3[3][4];
float arr4[4][5];
double arr5[4][5];

2.2 Initialization of two-dimensional array

int arr[3][4]={
    
    {
    
    1,2,3,4},{
    
    5,6,7,8},{
    
    9,10,11,12}};
char arr2[2][2]={
    
    {
    
    'a','b'},{
    
    'c','d'}};
int arr[3][4]={
    
    1,2,3,4,5,6};//一行只能放四个元素,当一行放满时,其余元素会自动放入下一行,当所有元素放完时,若此数组还有空间,默认填充0
int arr[][3]={
    
    {
    
    2,3},{
    
    4,5}};//二维数组初始化时,行可以省略,列不可以省略

Why rows can be omitted but columns cannot be omitted, see the memory storage analysis analysis below

2.3 Use of two-dimensional arrays

Two-dimensional arrays are also accessed through subscripts:

int main()
{
    
    
    int arr[3][4] = {
    
     0 };
    int i = 0;
    for (i = 0; i < 3; i++)//控制行
    {
    
    
        int j = 0;
        for (j = 0; j < 4; j++)//控制列
        {
    
    
            arr[i][j] = i * 4 + j;
        }
    }
    for (i = 0; i < 3; i++)
    {
    
    
        int j = 0;
        for (j = 0; j < 4; j++)
        {
    
     
            printf("%-2d ", arr[i][j]);
        }
        printf("\n");
    }
    return 0;
}

The output is:
insert image description here

2.4 Storage of two-dimensional arrays in memory

int main()
{
    
    
    int arr[3][4] = {
    
     0 };
    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;
}

![Insert picture description here](https://img-blog.csdnimg.cn/99c1bd41be714c20a5d5174809d91db9.png
From the above results, it can be analyzed that the elements of each row of the two-dimensional array are connected to the elements of the previous row. It can be seen that the two-dimensional array is also stored continuously in the memory.
Its storage method can be understood as this figure:
insert image description here
From this figure, we find that the column determines the number of elements, determines where each element is stored, and determines the address of each element. When we initialize a two-dimensional array, if If the column is omitted, it is impossible to indicate where each element is and how it is stored. On the contrary, when we omit the row, the number of elements in the column is clear. When allocating space for it, the specific location of each element can still be found .

3. Array out of bounds

The subscript of the array starts from 0. If the array has n elements, the subscript of the last element is n-1;
if the subscript of the array is less than 0 or greater than n-1, then the array access is out of bounds. C language It does not check the out-of-bounds of the array subscript, and the compiler may not report an error, but it does not mean that the program is correct.

#include <stdio.h>
int main()
{
    
    
  int i=0;
  int arr[10]={
    
    0};
  for(i=0; i<=10; i++)
  {
    
    
    arr[i]=i;//当i等于10,就访问越界了
  }
  return 0;
}

A warning will appear at runtime:
insert image description here
so pay attention to out-of-bounds checks

Fourth, the array as a function parameter

4.1 What is the name of the array?

In addition to two cases, the array name represents the address of the first element of the array

  • sizeof (array name), calculate the size of the entire array, put an array name inside sizeof, and the array name represents the entire array
  • &Array name, the address of the entire array is taken out

4.2 Attention to array parameter passing

Here is an example of bubble sort:

void bubble(int arr[5], int x)
{
    
    
	int i = 0;
	for (i = 0; i < x-1; i++)//控制趟数
	{
    
    
		int j = 0;
		for (j = 0; j < x - i - 1; j++)//每一趟比几次
		{
    
    
			if (arr[j] > arr[j + 1])//从小到大排序
			{
    
    
				int temp = arr[j];
				arr[j] = arr[j + 1];
				arr[j + 1] = temp;
			}
		}
	}
}
int main()
{
    
    
	int arr[5] = {
    
     5,4,3,2,1 };
	int sz = sizeof(arr) / sizeof(arr[0]);
	bubble(arr,sz);
	int i = 0;
	for (i = 0; i < sz; i++)
	{
    
    
		printf("%d ", arr[i]);
	}
	return 0;
}

This is the correct way of writing. When the receiving array is passed as the first element address, you can use the form of Int arr[] (the size can be omitted inside), but it is still a pointer in essence. Of course, you can also use int arr in the form of a pointer.

The wrong way to write is:

void bubble(int arr[5])
{
    
    
    int sz = sizeof(arr) / sizeof(arr[0]);
	int i = 0;
	for (i = 0; i < x-1; i++)
	{
    
    
		int j = 0;
		for (j = 0; j < x - i - 1; j++)
		{
    
    
			if (arr[j] > arr[j + 1])
			{
    
    
				int temp = arr[j];
				arr[j] = arr[j + 1];
				arr[j + 1] = temp;
			}
		}
	}
}
int main()
{
    
    
	int arr[5] = {
    
     5,4,3,2,1 };
	bubble(arr);
	int i = 0;
	for (i = 0; i < sz; i++)
	{
    
    
		printf("%d ", arr[i]);
	}
	return 0;
}

The main mistake is here:
insert image description here

If the size of the array is calculated inside the custom function, it should be noted that the array is passed by the address of the first element. I use int arr[] (the size can be omitted) to receive it, but it is still a pointer in essence, then sizeof(arr) seeks the size of a pointer, not the size of the array, so it is best to pass the size of the array along with it.

Guess you like

Origin blog.csdn.net/weixin_68201503/article/details/130665678