C language array: Explore the storage of one-dimensional arrays in memory


```c
#include<stdio.h>
int main()
{
    
    
	int arr[] = {
    
     1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
	int sz = sizeof(arr) / sizeof(arr[0]);//求数组中元素个数
	int i;
	int *p = arr;//指针变量p中存放arr[]首元素的地址
	for (i = 0; i < sz; i++)
		//printf("%p\n",&arr[i]);**打印出数组中各元素的地址,为了更直观的感受 修改一下printf里的内容**
		printf("arr[%d]=%p",i,&arr[i]);
} 


The difference between adjacent elements is exactly 4 bytes, which is an integer, which just shows that the array is stored continuously in the memory. Since it is stored continuously, as long as we know the name of the array (the array name is the address of the first element in the array), then the addresses of all elements can be found. (Using pointers)
Modify the code just now: `

#include<stdio.h>
int main()
{
    
    
	int arr[] = {
    
     1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
	int sz = sizeof(arr) / sizeof(arr[0]);//求数组中元素个数
	int i;
	int *p = arr;
	for (i = 0; i < sz; i++)
		printf("arr[%d]=%p<===>%p\n",i,&arr[i],p+i);
} 


(1). We can see that p+i changes by 1 every time i, but the effect changes by 4, so for an integer pointer variable, +1 is skipping an element. It can also be concluded that the pointer variable +1 (p+1) and the ordinary variable +1 int a; (a+1) are not comparable; and *(p+i) points to the first element The i-th element of.
(2) The storage order of the array in the memory changes from low to high as the subscript increases.

Guess you like

Origin blog.csdn.net/ahuyccc/article/details/110456367