Detailed notes of C language array

Posted by caine on Sat, 19 Feb 2022 01:37:42 +0100

array

A collection of elements of the same type

catalogue

1. Creation and initialization of one-dimensional array

2. Use of one-dimensional array

3. Storage of one-dimensional array in memory

4. Creation and initialization of two-dimensional array

5. Use of two-dimensional array

6. Storage of two-dimensional array in memory

7. Array as function parameter

Creation and initialization of one-dimensional array

Array creation

type_t   arr_name   [const n]
//Array type 	   name 		  quantity
int main()
{
   int arr[8];//Eight arrays of integer types are created. The array name is arr
    return 0;
}

Note that there must be a constant expression in []

C99 syntax support

Variable length array - the size of the array is a variable

vs2019 not supported

int main()
{
    int n=8;
    int arr[n];//error
    return 0;
}

Initialization of array

int main()
{
    int a=10;//initialization
    int arr1[10]={1,2,3,4,5,6,7,8,9,10};//Full initialization
    int arr2[10]={1,2,3,4,5};//Incomplete initialization
    return 0;
}

In case of incomplete initialization, the following values default to 0, as shown in the figure:

See the following initialization methods:

int arr[]={1,2,3,4,5}
int arr[5]={1,2,3,4,5}

These two codes are equivalent. When the number of array elements is not written, the system will count the number in your array by itself.

char ch1[5]={'b','i','t'};//b i t 0 0
char ch1[]={'b','i','t'};// b i t

ch1 is a character array. It is initialized to store b i t, and the default value of the remaining space is 0

char ch3[5]="bit";//b i t \0 0
char ch4[]="bit";//b i t \0

When the string is stored in the array, \ 0 is the end flag of the string, and \ 0 will be stored at the end of the string in the array

int main()
{
	char ch5[]="bit";
	char ch6[]={'b','i','t'};
    printf("%s\n",ch5);
    printf("%s\n",ch6);
    return 0;
}

When printing a string, it stops only when it encounters \ 0. By default, there will be a \ 0 end flag in ch5, but \ 0 is not stored in the character array ch6. The compiler cannot find the print end flag, so the printing is garbled.

Let's look at the following code:

int main()
{
	char ch5[]="bit";
	char ch6[]={'b','i','t'};
	printf("%d\n",strlen(ch5));//3
	printf("%d\n",strlen(ch6));//Random value
    return 0;
}

When strlen calculates the character length, \ 0 is the end flag. The ch5 array stores the string, and the default storage after t is \ 0. Therefore, there is an end flag, which is calculated as 3, while ch6 will not store \ 0 by default. Strlen cannot stop the calculation and prints the random value.

Use of one-dimensional array

int main()
{
    int arr[10]={0};//[] subscript reference operator
    arr[4] = 5;
    int sz=sizeof(arr)/sizeof(arr[0]);
    int i=0;
    for(i=0;i<sz;i++)
    {
        printf("%d",arr[i]);
    }
    return 0;
}

sizeof(arr) is the size of the total array, and sizeof(arr[0]) is the size of the first element because each element is the same size

Therefore, the total array size / the size of an element is the number of array elements.

The array we created is shown in the figure above. The subscript of the first element is 0. When accessing the array, we should pay attention to the following figure:

Storage of one-dimensional array in memory

int main()
{
    int arr[10]={0};//[] subscript reference operator
    int sz=sizeof(arr)/sizeof(arr[0]);
    int i=0;
    for(i=0;i<sz;i++)
    {
        printf("Subscript%d Your address is:%p\n",i, &arr[i]);
    }
    return 0;
}

%p is used to print the address

1. One dimensional arrays are stored continuously in memory. When we create an array, we actually open up a continuous space to store the array elements.

2. With the increase of array subscript, the address changes from low to high.

Creation and initialization of two-dimensional array

Creation of two-dimensional array

int arr[3][4];//Three rows and four columns
int main()
{
    int arr[3][4];//The first [] represents the number of rows and the second [] represents the number of columns
    double arr2[3][5];//double type two-dimensional array
    return 0;
}

Initialization of two-dimensional array

Assign values to while creating

int main()
{
    int arr1[3][4]={1,2,3,4,5,6,7,8,9,10,11,12}
    int arr2[3][4]={1,2,3,4,5};//Incomplete initialization of two-dimensional array
    int arr3[3][4]={{1,2},{3,4},{5}};
    
    double arr2[3][5];
    return 0;
}

If we want 1 and 2 in the first line, 3 and 4 in the second line and 5 in the third line, we treat a line as a one-dimensional array, and we can give them braces respectively.

We can omit rows to initialize the two-dimensional array. We have several rows that can be confirmed by initialization

int main()
{
    int arr[][4]={1,2,3,4,5};
    return 0;
}

However, column initialization cannot be omitted

Use of two-dimensional arrays

The use of two-dimensional array is also through subscript. The subscript of two-dimensional array is shown in the figure:

int main()
{
    int arr[3][4]={{1,2},{3,4},{5}};
    int i=0;//Number of rows
    int j=0;//Number of columns
    for(i=0;i<3;i++)
    {
        for(j=0;j<4;j++)
        {
            printf("%d ",arr[i][j]);
        }
        printf("\n");
    }
    return 0;
}

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-mwxrqsz6-1619258565445) (C: \ users \ 15191107746 \ appdata \ roaming \ typora \ typora user images \ image-20210421192458666. PNG)]

Storage of two-dimensional array in memory

int main()
{
    int arr[3][4]={{1,2},{3,4},{5}};
    int i=0;//Number of rows
    int j=0;//Number of columns
    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;
}

[the external chain image transfer fails. The source station may have anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-euypyz0h-1619258565446) (C: \ users \ 15191107746 \ appdata \ roaming \ typora \ typora user images \ image-20210421192813712. PNG)]

The difference between 28 and 2C is 4. We found that each adjacent address is 4. We found that the two-dimensional array is still stored continuously in memory. One row is continuous internally and across rows. With the increase of subscript, the address is still from low to high.

In fact, the storage of two-dimensional arrays in memory is:

When accessing a two-dimensional array, we can understand it as follows:

What is the meaning of memory layout? Look at the code below

One dimensional array:

int main()
{
    int arr[10]={1,2,3,4,5,6,7,8,9,10}
    int *p=arr;//The array name is the address of the first element
    int i=0;
    for(i=0;i<10;i++)
    {
        printf("%d ",*p);
        p++;
    }
    return 0;
}

According to the storage continuity, we can access each element of the array through the above code

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-osjaa90h-1619258565450) (C: \ users \ 15191107746 \ appdata \ roaming \ typora user images \ image-20210421194314406. PNG)]

2D array:

int main()
{
    int arr[3][4]={{1,2},{3,4},{5}};
    int i=0;//Number of rows
    int j=0;//Number of columns
    int *p=arr;//The array name is the address of the first element
    for(i=0;i<12;i++)
    {
        printf("%d ",*p);
        p++;
    }
    return 0;
}

We accessed every element in the two-dimensional array

Array as function parameter

We can't just print the array. We also need to give the array to the function as a parameter.

One dimensional array function parameter transfer use

void bubble_sort(int arr[],int n)
{
    int sz = sizeof(arr) / sizeof(arr[0]);//error
    int i = 0;
    for (i = 0; i < n - 1; i++)
    {
        int j = 0;
        for (j = 0; j < n - 1 - i; j++)
        {
            if (arr[j] > arr[j + 1])
            {
                int temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
            }
        }
    }
}
int main()
{
    
    int arr[] = { 1,2,4,3,7,6,5,8,10,9 };
        //Sort - sort in ascending order
    int sz = sizeof(arr) / sizeof(arr[0]);
    bubble_sort(arr, sz);//Bubble sorting
    for (int i = 0; i < sz; i++)
    {
        printf("%d ", arr[i]);
    }
    return 0;
}

We cannot calculate the number of array elements inside the function, because the array name is passed into the function, the array name is the address of the first element, and the address should be accepted by the pointer. Under the 32-bit operating system, the size of the pointer is 4 bytes and sizeof(arr) is 4 bytes. Therefore, the number of array elements calculated inside the function is 1, so the sorting cannot be completed naturally.

int main()
{
   	int arr[] = { 1,2,4,3,7,6,5,8,10,9 };
    //In most cases: the array name is the address of the first element
    //There are two exceptions:
    //Sizeof (array name) - the array name represents the entire array and calculates the size of the entire array
    //&Array name - the array name represents the whole array, and the address of the whole array is taken out
    printf("%p\n",arr[0]);
    printf("%p\n",arr);
    return 0;
}


In most cases: the array name is the address of the first element
There are two exceptions:
Sizeof (array name) - the array name represents the entire array and calculates the size of the entire array.
&Array name - the array name represents the whole array, and the address of the whole array is taken out.

Parameter transfer and use of two-dimensional array function

void print_arr(int arr[3][4],int row,int col)
{
   int i=0;
   int j=0;
   for(i=0;i<row;i++)
   {
      for(j=0;j<col;j++)
      {
          printf("%d ",arr[i][j]);
      }
   }
}
int main()
{
   int arr[3][4]={1,2,3,4,5,6,7,8,9};
   print_arr(arr,3,4);
   return 0;
}

Welcome to learn and exchange!

Topics: C array