当前位置:网站首页>Comprehensive analysis of C array

Comprehensive analysis of C array

2022-06-12 23:04:00 A fierce wolf

C Array Comprehensive analysis

Array name

The value of the array name is a pointer constant , That is, the address of the first element of the array . Its type depends on the type of array element .

​ Only on two occasions , Array names are not represented by pointer constants -------

​ ①sizeof( Array name ), Calculate the size of the entire array ,sizeof Inside A separate Put an array name , The array name represents the entire array .sizeof Returns the length of the entire array .

​ ②& Array name , What we get is the address of the array .& Array name , The array name represents the entire array . Taking the address of an array name produces a pointer to Pointer to array .

// Code understanding 
int a   //a It's an integer 
int b[10]  //b It's an array of integers , The length is 10  Array name b  Is the first element of the array  int  Type of address ,  A pointer to an integer  int *p
int c[3][6]//c Is a two-dimensional array ,3 That's ok 6 Column   Array name c  Is the first element of the array  int [6]  Type of address ,  One point   Pointer to array  int (*p)[6]
// Understanding of constants 
p=&arr[0]  ==   p=arr    
arr[5]     ==   *(arr+5)   == *(p+5)
// Be careful   stay ++ In the operator  p++ Can achieve ,  however arr++ It can't be done , Because the array name arr Is a pointer constant 
 

 Insert picture description here

Multidimensional arrays are also stored consecutively in memory ! Therefore, multidimensional array parameter transfer can also be used First level pointer to receive . But never use a two-dimensional pointer to receive . The details will be explained later .

​ Understanding of multidimensional arrays : The implementation box represents the first dimension 3 Elements , Dashed lines are used to divide the second dimension 6 Elements ,

​ The value of a dimension group name is a pointer constant , Its type is " Pointer to element type ", It points to the... Of the array 1 Elements . Multidimensional arrays are almost as simple . The only difference is multidimensional arrays ** The first 1 The dimension element is actually another array **

​ Such as int c [3] [6] It can be seen as a one-dimensional array , contain 3 Elements , Each element just happens to contain 6 Array of integer elements .

Array name c The value of points to its th 1 Addresses of elements , That is, a point contains 10 Pointer to an array of integer elements namely c [6]

​ When performing array name pointer operation , The pointer will skip The size of the first element is

	// Code example 
	int mat[3][6]; // Define a two-dimensional array 
	mat[1][5]  // visit   In a two-dimensional array   In the first row and the fifth column   Elements 
    *(mat+1)  //  One points to the second row of the array   The pointer to the array of   Equivalent to  mat[1] 
    *(mat+1)+5  // It's a pointer  . Point to 1 Xing di 6 Elements   namely  &mat[1][5]
    *(*(mat+1)+5)  //  It's exactly equivalent to  a[1][5] 
    

Subscript

​ In addition to priority , Subscript reference and indirect access are exactly the same , Where subscripts are used , Equivalent pointers can be used instead of . For example, the following 2 Expressions are equivalent

  array[i];
  *(array+i);
// Even the following expression is valid , But it is not recommended to write this , Because the readability is too poor 
 2[array];
*(2+(arry));// Equivalent conversion 
*(array+2);// Equivalent conversion 

Pointers are sometimes more efficient than subscripts , But the improvement in efficiency is negligible , Let's not elaborate here , Interested bosses can read <<C And a pointer >> This book , Most of the content of this article is also drawn from the book .

Pointer array

​ Except type , Pointer variables are very similar to other variables . Just as you can create an integer array , You can also declare a pointer array . for example

int *api[10];

​ To clarify this complex statement , Let's assume it's an expression , And evaluate him

​ Subscript references take precedence over indirect access , So in this expression , Execute subscript reference first . therefore api Is some kind of array ( By the way , It contains a number of elements 10 individual ). After getting an array element, the indirect access operator is executed immediately . This expression has no other operators , So the result is an integer value .

​ that api What is it ? After performing an indirect access operation on an element of the array , We get an integer value , therefore api It must be an array , Its element type is a pointer to an integer .

// Code example 
char const *keyword[]={
    
    "good",
    "morning",
    "afterno",
    "evening",
    NULL        
};
int sz=sizeof(keyword)/sizeof(keyword[0]) // Count the number of elements in the array ,
    //sz=sizeof(keyword)  Calculate the bytes occupied by the entire array  ,sizeof(keyword[0]) Calculate the bytes occupied by each element of the array 
    // Particular attention  keyword[0]  The type of  char* , That is, string constants , stay 32 By default, it takes up 4 Bytes 
    
    
    
// Comparison code 
    char const keyword[][10]={
    
    "good",
    "morning",
    "afternoom",
    "evening",
    NULL        
};
 // Although the number of array elements is the same , But if you define it this way ,
// however sizeof(keyword[0]) Calculate the bytes occupied by each element of the array   Is the second dimension of the array ,  namely char [10]  Occupy 10 Bytes 
// This creates a waste of space 

therefore , People tend to prefer the pointer array scheme .

Array parameters

One dimensional array parameters

​ Through the study , We should now know that the value of an array is an address that points to the first element of the array , So it is easy to see that a copy of the pointer is passed to the function at this time .

So an array parameter can be declared as an array , It can also be declared as a pointer . Be careful : These two declarations are equal only when they are formal parameters of a function

// Code example 
int arr[10];
void test(int arr[])//
{
    }
void test(int arr[10])// actually , Because the array passes parameters , Just pass the address of the array ,c When a function passes parameters, it doesn't really care about the length of the array , Nor can we know the length of the array through parameters 
{
    }
void test(int *arr)//
{
    }
// All three declaration methods are OK 

Multidimensional array parameter transfer

Conventional methods

​ Multidimensional array names as function parameters are passed in the same way as one-dimensional array names ----- What is actually passed is a pointer to the first element of the array .

​ But the difference between the two is , Each element of a multidimensional array is itself another array , The compiler needs to know its dimensions , So that the function subscript expression can be evaluated

summary : When a multidimensional array name is passed as a parameter to a function , Its formal parameter design can only omit the first dimension , Only in this way can the compiler calculate

Bear in mind : Never declare an array parameter as a second level pointer

// Code example 
int arr[3][5];
void test(int (*arr)[5]);
void test(int arr[][5]);

// Error code 
void test(int **arr);// This example puts arr A pointer declared as a pointer to an integer , It is not the same thing as a pointer to an integer array 

Special methods ( Squash array (“flattening the array”))

​ Although the compiler may warn in this way , however The essence of each element of a multidimensional array is its basic data type , And multidimensional arrays are stored continuously in memory , So we can directly declare a first-class pointer to its basic data type as a formal parameter to receive its address , This technique is called Squash array ,

​ If you need to pass a two-dimensional array to the function , I don't want to give the length of the second dimension in the function prototype , Then you can use this method .

int arr[3][5];
void test(int *arr,int row,int col); // Receive using a one-dimensional pointer 
*(Mat+(i*col)+j) ===Mat[i][j]	// Accessing array elements  i*row  Jump to the specified line  +j Skip to the specified column 
				//ps  Although compilers and books may not recommend this method , But I think this method only needs to master the relationship between pointer and array , It is more convenient to use 
// Code example 
// There is a matrix of numbers , Each row of the matrix is incremented from left to right , The matrix is increasing from top to bottom , Please write a program to find out whether a number exists in such a matrix .
// requirement : Time complexity is less than O(N);

// Conventional methods 
int findnum(int a[][3], int x, int y, int f) // The type of the first parameter needs to be adjusted 
{
    
	int i = 0, j = x - 1; // Start from the top right corner and traverse 

	while (j >= 0 && i < y)
	{
    
		if (a[i][j] < f) // Older than me, down 
		{
    
			i++;
		}
		else if (a[i][j] > f) // He left when he was younger than me 
		{
    
			j--;
		}
		else
		{
    
			return 1;
		}
	}
	return 0;
}
// Special methods ( Squash array )
int search(int *Mat ,int Des , int row, int col){
    
	int i = 0, j = (col - 1);			// Start at the top right corner and look for 
	while (j >= 0 && i < row){
    
		if( *(Mat+(i*col)+j)<Des){
    			//*(Mat+(i*col)+j)  Equivalent to Mat[i][j]
			i++;
		}
		else if (*(Mat+(i * col) + j) > Des){
    
			j--;
		}
		else return 1;
	}
	return 0;
}
// Test functions 
int main(){
    
	int mat[4][5] = {
     {
     1, 2, 3,4,5 },
						{
    5,6,7,8,9},
					{
    10,11,12,13,14},
					{
    15,16,17,18,19} };
	if (search(mat , 19, 4, 5)) printf("yes\n");
	else printf("no\n");



	return 0;
}

Supplementary picture understanding :

Understanding of array pointers :

 Array pointer

Understanding of pointer array :

 Pointer array

Multidimensional arrays and Understanding of squashing arrays :

 Multidimensional array and array flattening

原网站

版权声明
本文为[A fierce wolf]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202281115103847.html