[C language] Array detailed answer

The essence of an array is a collection of variables of the same type, put together.
The following is the program code I completed without using an array, taking the input of student grades as an example.

#include<stdio.h>
int main()
{
    
    
	int uchida;
	int satoh;
	int hiraki;
	int masaki;
	int sum = 0;
	int sanaka;
	printf("请输入5名学生的分数:\n");
	printf("1号:");
	scanf("%d", &uchida);
	sum += uchida;
	printf("2号:");
	scanf("%d", &satoh);
	sum += satoh;
	printf("3号:");
	scanf("%d", &hiraki);
	sum += hiraki;
	printf("4号:");
	scanf("%d", &masaki);
	sum += masaki;
	printf("5号:");
	scanf("%d", &sanaka);
	sum += sanaka;
	printf("总:%5d\n", sum);
	printf("平均分:%5.1f\n", (double)sum / 5);
	return 0;
}
   如果学生的人数不是5人而是200人的时候会怎么样呀?为了保存分数,需要创建200个变量,还要管理这200个变量名。编写程序的时候就很麻烦,还要注意变量名不能输入错误。变量名、号码不同,但是每次执行的都几乎相同的处理。

Arrays are good at dealing with this type of data , which can collect and manage variables of the same data type through "numbers".
Code done with arrays:

#include<stdio.h>

int main()
{
    
    
	//定义数组的长度为5并且初始化数组元素全部为0
	int arr[5] = {
    
     0 };
	int sum = 0;
	//这里要多组输入使用循环来控制输入
	for (int i = 0; i < 5; i++)
	{
    
    
		printf("请输入第%d学生成绩:",i+1);
		scanf("%d", &arr[i]);
	}
	//遍历数组的元素并求和  
	//创建一个变量来接收和
	for (int i = 0; i < 5; i++)
	{
    
    
		sum += arr[i];
	}
	//打印学生的总成绩和平均成绩
	//计算平均成绩的时候使用强制类型转换,这样才能保留小数
	printf("学生的总成绩=%d\n", sum);
	printf("学生的平均成绩=%0.1f\n", (double)sum / 5.0);
	return 0;
}

The advantage of writing this way is that

  • Can improve code readability
  • Reduce the creation of variables, that is, reduce the fault tolerance rate of the program

Note:
Arrays can be used to implement collections of objects of the same type.

Creation and initialization of one-dimensional arrays

array declaration

Arrays are declared by specifying the element type, variable name, and number of elements.

Array creation

How the array is created:

type_t   arr_name   [const_n];
//type_t 是指数组的元素类型
//const_n 是一个常量表达式,用来指定数组的大小

An instance of array creation:

//代码1
int arr1[10];
//代码2
int count = 10;
//此时数组不能正常的创建,因为数组个数必须为常量
int arr2[count];
//代码3
char arr3[10];
float arr4[1];
double arr5[20];

** Note: **
When creating an array, before the C99 standard, a constant must be given in [], and variables cannot be used. However, the C99 standard supports the concept of variable-length arrays. The size of the array can be specified using variables, but the array cannot be initialized. It mainly depends on whether the compiler used supports variable-length arrays in C99.

Array initialization

  • Array initialization refers to giving some reasonable initial values ​​(initialization) to the contents of the array while creating the array.
  • When the array is created, if you don't want to specify the definite size of the array, you have to initialize it. The number of elements in the array is determined according to the initialization content.
//数组的初始化
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' };//字符数组中的98是对应ASCII码值中的字符
char arr5[] = {
    
     'a','b','c' };//数组的内容是不可预测的,因为字符数组元素是以'\0',为结束标志
char arr6[] = "abcdef";//此数组会自动添加'\0'

The following is the length, printed content and storage method of the arr5[] array I tested

#include<stdio.h>

int main()
{
    
    
	char arr5[] = {
    
     'a','b','c' };
	
	printf("%s\n", arr5);
	return 0;
}

This is the character stored in the array. It can be seen that the end mark '\0' is not generated;
image.png
this is the content printed by the array. It can be seen that the printed content is not all the content in our array, because there is no end mark.

The following is the result of the end flag code I manually added and printed.

#include<stdio.h>
int main()
{
    
    
	char arr5[] = {
    
     'a','b','c','\0' };

	printf("%s\n", arr5);
	return 0;
}

image.png
Summary:
So the end print mark of the character array is '\0'.

Use of one-dimensional arrays

Assign values ​​1-10 to the array, and print the array elements.

#include<stdio.h>

int main()
{
    
    
	//定义一个数组并初始化为0
	int arr[10] = {
    
     0 };
	//使用循环赋值
	for (int i = 0; i < 10; i++)
	{
    
    
		arr[i] = i + 1;
	}
	//使用for循环打印数组的值
	for (int i = 0; i < 10; i++)
	{
    
    
		printf("%d ", arr[i]);
	}
	return 0;
}

The result of running the program is as follows:
image.png

  • Arrays are accessed using subscripts, which start at 0.
  • The size of the array can be calculated.
int arr[10];
int sz = sizeof(arr)/sizeof(arr[0]);

Storage of one-dimensional arrays in memory

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

image.png
It can be seen that the one-dimensional array is stored continuously in the memory, and the address is from low to high.

Creation and initialization of two-dimensional arrays

A two-dimensional array is like a form consisting of "rows" and "columns", where the elements are arranged vertically and horizontally.

Creation of two-dimensional array

//数组创建
int arr[3][4];
char arr[3][5];
double arr[2][4];

Initialization of two-dimensional array

//数组初始化
int arr[3][4] = {
    
    1,2,3,4};
int arr[3][4] = {
    
    {
    
    1,2},{
    
    4,5}};
//二维数组如果有初始化,行可以省略,列不能省略
int arr[][4] = {
    
    {
    
    2,3},{
    
    4,5}};

Use of two-dimensional arrays

Two-dimensional arrays are also accessed through subscripts

#include <stdio.h>
int main()
{
    
    
	//创建一个3行4列的二维数组 赋值为0
	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("%d ", arr[i][j]);
		}
	}
	return 0;
}

It can be seen that the two-dimensional array uses two loops to traverse, one loop is to traverse the rows of the array, and the other is to traverse the columns. How to traverse the three-dimensional array?
In fact, we can infer that the three-dimensional array is traversed using three loops, and so on.

Storage of two-dimensional arrays in memory

Let me use the code to see how the two-dimensional array is stored in memory

#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;
}

image.png
Through the results, we can analyze that the two-dimensional array is also stored continuously in the memory, and the address is also from high to low.

Array out of bounds

  • The subscript of the array is limited in scope;
  • 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, it means that the array is accessed out of bounds, and the access exceeds the legal space of the array;
  • The C language itself does not perform out-of-bounds checks for array subscripts, and the compiler may not necessarily report an error, but the fact that the compiler does not report an error does not mean that the program is correct. Therefore, when programmers write code, it is best to do out-of-bounds checks by themselves.
#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]);//当i等于10的时候,越界访问了
    }
    return 0;
}

image.png
It can be seen that the last value of the array is not a value that we can control. This is because the array is accessed out of bounds, so we must pay attention to the out-of-bounds access of the array when writing.
The above is my detailed answer to the array, if there is something wrong, please comment and correct me. thank you all.

Guess you like

Origin blog.csdn.net/weixin_63284756/article/details/130649954