The nature of the array
- An array is a contiguous amount of memory space
- The space size of the array is sizeof (Array_type) *array_size
- The array name can be seen as a constant pointer to the first element
Operation of Pointers
A pointer is a special variable, with an integer operation rule of
p+n; <--> (unsigned int) p + n * sizeof (*P);
Conclusion :
When the pointer p points to an element of an array of the same type, p+1 points to the next element of the current element; p-1 points to the previous element of the current element.
Only subtraction operations are supported between pointers, and the type of pointers involved in subtraction must be the same.
Note :
- Pointer subtraction is only meaningful when two pointers point to an element in the same array, meaning the subscript difference of the element to which the pointer refers
- When two pointers point to an element that is not in the same array, the result is undefined
Example 1: Application of pointer arithmetic
#include <stdio.h> #define DIM (a) (sizeof (a)/sizeof (*A)) intMain () {CharS[] = {' H ', ' e ', ' l ', ' l ', ' o '};Char* Pbegin = s;Char* PEnd = s + DIM (s);//Key Point Char* p = NULL; printf"Pbegin =%p\ n", Pbegin); printf"pEnd =%p\ n", pEnd); printf"Size:%d\ n", Pend-pbegin); for(P=pbegin; p<pend; p++) {printf ("%c", *p); } printf ("\ n");return 0; }
Comparison of pointers
- Pointers can also be compared in relation (<,>,<=,>=)
- The premise of pointer relational operations is to point to elements in the same array at the same time
- Comparison operation between any two pointers (==,=!) Unlimited
- The pointer type must be the same for participating in the comparison operation
Summary
- Array declaration when the compiler automatically allocates a contiguous memory space
- The pointer declaration is only assigned a 4-byte space to hold the address value
- Pointers and integers can be operated with the result of pointers
- Subtraction is supported between pointers, resulting in an array of element subscript deviations
- Comparison operations are supported between pointers and must be of the same type
Array and pointer analysis