pointer
foreword
To record the storage location of a data object in memory, two pieces of information are required:
1. The first address of the data object.
2. The size of storage space occupied by data objects
The size of the memory space (bytes) occupied by the basic data type, one byte represents 8 binary bits
char 1
short 2
int 4
long 4
long long 8
float 4
double 8
pointer data type
The address-of operator &
You can get the first address of the data object and the size of the required storage space
declare pointer type
int n; int* pn=&n;
The value of the pointer type is the first address of the target data object!
In the C language, different pointer types are used to mark the space size of the target data object, so can different data types assign values to each other?
for example:
#include <stdio.h> int main() { int n; int *pn=&n; char y; char *py=&y; pn=py; printf("pn=%u\n",pn); printf("py=%u\n",py); return 0; }
Since the space occupied by the char and int types is different, automatic conversion cannot be performed.
value operator*
Find the target data object according to the first address and space size stored in the pointer.
Note: %p is a special site symbol for pointer types, and it can be printed correctly under 32 and 64-bit compilation conditions.
You can also use the pointer to modify the data object pointed to and access the data object
pointer type size
Note: char and int store two types of data with different data ranges, the char type occupies a smaller space, and the int occupies a larger space. Both char* and int* store the addresses of data objects, and they occupy the same space.
cast pointer type
Int type pointers and char type pointers cannot be automatically converted using assignment, if forced conversion is used.
We can see the following program, which forcibly converts pn into char * and assigns it to pc, and then looks at the running results, the two initial addresses and values are consistent.
pointer arithmetic
Pointer type address addition and subtraction rules
After adding n to the pointer type, the first address moves backward by n*step bytes.
After subtracting n from the pointer type, the first address moves forward by n*step bytes.
Note: The value operator * has a higher precedence than the arithmetic operator.
array
access array method
1. Array name [subscript]
2. *(array name + offset) where the offset represents the number of elements that differ
pointer passed as parameter
Pointer type void * with only the first address
The pointer whose type is void * only saves the first address, and does not save the space size of the target data object.
void *Benefits: Any type of pointer can be directly assigned to it.
For specific documents, see GitHub