Problem
If the array name can be used as a constant pointer, will the pointer also be used as an array name?
How arrays are accessed
- Access the elements in the array in the following form
- Accessing elements in an array as pointers
Subscript form vs Pointer form
- The efficiency is higher than the subscript when the pointer moves in the array in fixed increments
- Higher efficiency when the pointer increment is 1 and the hardware increments the model
- The conversion of subscript form and pointer form
Attention:
The generation code optimization rate of modern compilers has been greatly improved, and in fixed increments, the efficiency of subscript forms is quite the same as that of pointers; but from the point of view of readability and code maintenance, the subscript form is more excellent.
Example 1: Arrays and pointers
#include <stdio.h>intMain () {inta[5] = {0};int* p = A;inti =0; for(i=0; i<5; i++) {P[i] = i +1; } for(i=0; i<5; i++) {printf ("a[%d] =%d\ n", I, * (A + i)); } printf ("\ n"); for(i=0; i<5; i++) {I[a] = i +Ten; } for(i=0; i<5; i++) {printf ("p[%d] =%d\ n", I, p[i]); }return 0;}
The difference of a and &a A is the address of the first element of the array &a the address of the whole
Example 2: pointer arithmetic classic problem
#include <stdio.h> intMain () {inta[5] = {1,2,3,4,5};int* P1 = (int*) (&a +1);int* P2 = (int*)((int) A +1);int* P3 = (int*) (A +1); printf"%d,%d,%d\ n", p1[-1], p2[0], p3[1]);return 0; }//A. Array subscript cannot be negative, program cannot run//B. p1[-1] Outputs a random number, p2[0] Output 2, p3[1] Output 3//C. p1[-1] Output garbled, p2[0] and p3[1] outputs 2
Array parameters
When an array is used as a function parameter, the compiler compiles it to the corresponding pointer
Conclusion :
In general, when you have an array parameter in a defined function, you need to define another parameter to indicate the size of the array
Summary
- Array names and pointers are only used the same way
- The nature of the array name is not a pointer
- The nature of the pointer is not an array
- The array name is not the address of the array but the address of the first element of the array
- Array parameter of function degenerate to pointer
Pointers and Arrays