Define an array here casually
int arr[5];
Arr is now the array name, and arr represents the entire block of memory for that array, that is, sizeof (arr) = = 20 (assuming sizeof (int) = = 4), the content in Arr is the first address of that block of memory, arr = = &arr[0]. Arr can be seen as a constant, and it is not possible to use operations such as arr++.
int *p;
p = arr;
P is a pointer to the int type, p = arr, which is the first address of the array (the content of ARR is the first address of the array, the previous analysis) assigns p, that is, p is now pointing to the first address of the array, the entire array can be accessed by P, but p is just a pointer variable, that is, p Change, p cannot represent the entire array of memory like arr, so sizeof (p) = = sizeof (int*)! = sizeof (arr).
The first address of the array is assigned to P, but the essence of P is an int type pointer variable, so you can perform operations such as + + on p.
We can access the elements in the array by an offset to P, arr (int type pointer +1 or-1, which is either up or down, sizeof (int) byte), * (P + i), * (arr + i), or by traditional arr[i] Accesses an array.
For example (from the teacher's lecture):
int a[5] = {1, 2, 3, 4, 5};
int *ptr = (int*) (&a + 1);
printf ("%d,%d", * (A + 1), * (ptr-1));
What should be the value of the output here?
A is represented (not pointing) to the entire array of memory, the value of a is the first address of the array memory, the address of a (&a), that is ..., so here the &a is a block of memory pointing to the entire array, so the value of a is the same as the value of &a, which is the first address of the array, but they The meaning is not the same.
Here &a each offset is to move the entire memory block size, here is the move sizeof (a), that is, the &a + 1, so here is the pointer down 40byte (the size of the array memory block), &a+1 's point is the next sizeof (a ) The size of the memory block.
Here is the memory allocation diagram:
&a---> ========== assume that the address value here is 0x11111111 &a and the value of a is 0x11111111
|| 1 | |
==========
|| 2 | |
==========
|| 3 | |
==========
|| 4 | |
========== <-----ptr-1 int type of pointer each offset is sizeof (int) bytes
|| 5 | |
&a +1---> ========== <-----ptr the pointer ptr on the INT type points to the above topic.
|| ? ||
==========
|| ? ||
==========
|| ? ||
==========
|| ? ||
==========
|| ? ||
&a+2---->==========
|| ? ||
==========
""""""
""""""
""""""
So the output of the above topic is:
2,5
All of these are my personal understanding of pointers and arrays in C, if anything is wrong, please point it out!
C in array and pointer "go"