Pointer and array 1

Keywords: C Visual Studio

Let's take a look at such an example. There is an operation of pointer to refer to array

//Enter ten numbers and output from large to small
#include<stdio.h>
void sort(int x[],int n);
int main(void){
    int i,*p,a[10];
    p=a;     //Get address
    for(i=0;i<10;i++)
      scanf("%d",p++);//Continuous input
      p=a;      //Fetch address again
      sort(p,10);//Function reference
    for(p=a,i=0;i<10;i++)//Continuous output
       { printf("%d",*p);
          p++;
        }
     printf("\n");
     return 0;
 }
void sort(int x[],int n){
   int t;//Null variable
   for(int i=0;i<n-1;i++)//Bubble sorting method. The first for loop determines the number of rounds of the loop
      for(int j=0;j<n-1-i;j++)//Compare the size of each number with the following one, and put the large one forward
         if(x[j]<x[j+1]){
           t=x[j];x[j+1];x[j+1]=t;}
}

We know that each element in the array has its own address. Using pointers, we can quickly reference array elements

The above example is a relatively simple one-dimensional array. First let p=a, (p = & A) to reference the next element, just p + +. This is equivalent to adding one to the address. Naturally, we can get the address of the next element. OK, let's take a look at this expression again

#include<stdio.h>
int main(void) {
	int a[] = { 1,2,3,4 };
	printf("%d", *a);
	return 0;
}
//*a=*&a

Obviously, the array name here is preceded by * because the array name represents the address of the first element, so adding * changes the value of the first element, that is, * a = * & A

Let's look at the following expression

t=*(x+j);*(x+j)=*(x+j+1);*(x+j+1)=t; 

Here is the same as the function of the expression in the example. You can see that x[j]=*(x+j). The j-th element in the array can be represented by a pointer. It can be understood that x is the first address of the array, which is 0. If j=3, x[2] is the value of the third element in the array, (x+2) is the address of the third element, plus the value of "*", the two formulas are equal.

Let's take a brief look at the pointer application of a one-dimensional array. OK, let's take a look at multi-dimensional arrays

int a[][4]={{1,3,5,7},{9,11,13,15},{17,19,21,23}};

Defines a two-dimensional array with three rows and four columns

How can the address of each element in a two-dimensional array be represented by a pointer?

Example: find 5, the third in the first line

#include<stdio.h>
int main(void) {
	int a[][4] = { {1,3,5,7},{9,11,13,15},{17,19,21,23} };
	
	printf("%d",*(*(a+0)+2 ));//a[0][2] *(a[0]+2 )
	return 0;
}

You can see * (* (a+0)+2)=*(a[0]+2)=a[0][2]

a[0][2] don't explain too much. It's the general method of arrays

*(a[0]+2) a[0] is the first address of the first row, and + 2 is the column change. Move 2 addresses to the right, that is, the address of the third element

*(* (a+0)+2) first look at * (a+0), which is the first address of the first line of a + 0, the line transformation + 0, that is, the first address of the first line, and then + 2, that is, the first address of the third element of the first line

printf("%d", *(*(a + 1)+2));

The output like this is 13, because * (a+1) is line + 1, that is, the first address of the second line

We can get such a standard form: * (* (a+i) + j). Here, + i is doing row change and + j is doing column change. We can find the address of each element in the two-dimensional array in this way

If it is inconvenient to understand, here is the formula for converting memory:

*(*(a+i)+j) ==*(*&a[i]+j)==*(a[i]+j)==*&a[i][j]==a[i][j]

OK, let's think about the output of the following expressions

#include<stdio.h>
int main(void) {
	int a[][4] = { {1,3,5,7},{9,11,13,15},{17,19,21,23} };
	
	printf("%d,%d\n", a,*a );
	printf("%d,%d\n", a[0], *(a+0));
	printf("%d,%d\n", &a[0], &a[0][0]);
	printf("%d,%d\n", a[1], a+1);
	printf("%d,%d\n", &a[1][0], *(a+1)+0);
	printf("%d,%d\n", a[2], *(a+2));
	printf("%d,%d\n", &a[2], a+2);
	printf("%d,%d\n", a[1][0], *(*(a+1)+0));
	printf("%d,%d\n", *a[2], *(*(a+2)+0));
	return 0;
}

answer:

  Let's analyze one by one: (first, it is clear that a is defined as follows: a[][4])

1.a is the first address of the array. What is printed is the address, which is a random value, * a is not the value in the first address, * a is the value of the first address of a, so the output result is also a random value

2.a[0] is the address * a[0] is the value in the address, * (a+0)=*a, as above

3. & A [0] is also an address, & a[0][0], a[0][0] is the correct way to write, but adding a & in front is equivalent to taking the address again

4.a+1 is obviously the addition and subtraction of the address, that is, a [0] + 1 = & A [0] [1]

5-7. The reason is the same as above

8. Previous standard method

9.*a[2]=*(a[2]+0), that is, the value in the first address of the third line

We must be familiar with the meaning of these expressions, or we will suffer losses in the operation of looking at the code and typing the code later, and we will fail in the exam (don't ask me how I know)

OK, let's try the ox knife

Reference multidimensional array through pointer example 1:

#include<stdio.h>
int main(void) {
	int a[][4] = { {1,3,5,7},{9,11,13,15},{17,19,21,23} };
	int* p;
	for (p = a[0]; p < a[0] + 12; p++) {
		if ((p - a[0]) % 4 == 0)
			printf("\n");
		printf("%4d", *p);//4 is the width and alignment is required
	}

	return 0;
}

result:

  The above uses a pointer to output all the elements of the array. To accurately output the elements of a row and a column, we need to use the array pointer to see this example:

#include<stdio.h>
int main(void) {
	int a[][4] = { {1,3,5,7},{9,11,13,15},{17,19,21,23} };
	int (*p)[4],i,j;//Define array pointer (* p)[4]
	p = a;
	scanf("%d%d", &i, &j);
	printf("%d", *(*(p + i) + j));
	return 0;
}

p is a pointer to an array with four integer elements. Many beginners (I) can't figure out what pointer, array pointer, pointer array, don't worry, give it a try and think about it

The following is an error code

#include<stdio.h>
int main(void) {
	int a[][4] = { {1,3,5,7},{9,11,13,15},{17,19,21,23} };
	int *p,i,j;
	p = a;
	scanf("%d%d", &i, &j);
	printf("%d", *(*(p + i) + j));
	return 0;
}

Error display

 

  Think carefully about the relationship between pointers and arrays. The array name is a pointer. The above code can be as follows:

#include<stdio.h>
int main(void) {
	int a[][4] = { {1,3,5,7},{9,11,13,15},{17,19,21,23} };
	int i,j;
	scanf("%d%d", &i, &j);
	printf("%d", *(*(a + i) + j));
	return 0;
}

Now, it is required to reference with a pointer. I only define a pointer such as * p so that p=a. in this way, p is equivalent to a one-dimensional array. It should be used for reference as follows:

#include<stdio.h>
int main(void) {
	int a[][4] = { {1,3,5,7},{9,11,13,15},{17,19,21,23} };
	int i,*p;
	p = a;
	scanf("%d", &i);
	printf("%d", *(p+i));
	return 0;
}

If I want to find the number 21, I have to input 10 to output 21, which can not meet the requirements of several rows and columns. Therefore, we should now understand that the array pointer corresponds to a two-dimensional array

The array pointer used above, that is (* p)[4], is a pointer

The following uses the pointer array, * p[4], which is an array

(the essence of the difference between (* p)[4] and * p[4] above is priority () > [] > *)

#include<stdio.h>
int main(void) {
	int a[] = { 100,200,300 };
	int i, *p[3];//Define pointer array * p[3]
	for (i = 0; i < 3; i++)
		p[i] = &a[i];
	for (i = 0; i < 3; i++)
		printf("a[%d]=%d\n", i, *p[i]);

	return 0;
}

This is the simplest example of pointer array. At first glance, some people may ask, what's P in this definition? Isn't it an array, and then give the elements in array a to P. no, no, every element in the pointer array is a pointer type. What's this called? It's not that a family doesn't enter a house. This house is full of pointer types, so p[i] =& A [i]; is to give a pointer to the address of an element in A. Oh, you will understand that this is not the original appearance of the pointer. Just give it the address, and then, * p[i] prints out the value of the element in the address pointed to by the pointer.

Let's look at an array of pointers of type char

#include<stdio.h>
int main(void) {
	char* name[] = { "a","b","c","d" };
	for (int i = 0; i < 4; i++) {
		printf("name[%d]=%s\n", i, name[i]);	
	}
	return 0;
}

Output results:

  OK, let's note that for char type, one character takes up one byte, and for int type, one takes up four bytes. Here, I add one name[i] each time to get the first address of each character, that is, I change a, B, C and D into longer words, and print out the four single words

  Next, let's look at the example after adding the function:

//This is the four subject scores of three students. It is required to print the average of all scores of three students and the four subject scores of the third student
#include<stdio.h>
void average(float* p, int n);//Declarative function
void search(float(*p)[4], int n);
int main(void) {
	float score[][4] = { {65,66,70,60},{80,87,90,81},{90,99,100,98} };
	average(*score, 12);//Reference function
	search(score, 2);
	return 0;
}
void average(float* p, int n) {
	float* p_end;
	float sum = 0, aver;
	p_end = p + n - 1;//In the main function, n=12, a total of 12 scores. In the main function, p is score. Here is the first address. Because it accounts for one item, it needs - 1
	for (; p <= p_end; p++)
		sum = sum + (*p);//Add up all your grades
	aver = sum / n;//Average
	printf("average=%5.2f\n", aver);//Keep two decimal places
}
void search(float(*p)[4], int n) {
	for (int i = 0; i < 4; i++)//Print the student's four subjects
		printf("%5.2f ", *(*(p + n) + i));//Here is the standard reference method, which has been highlighted above
	printf("\n");
}

Print results:

  OK, that's all for this chapter. If there are omissions and mistakes, please correct them. Thank you.

Posted by smilesmita on Wed, 01 Dec 2021 20:20:15 -0800