C language: access array elements with pointers:

Task code:

(as follows)

Implementation:


Knowledge summary :

Knowledge point 1: Use pointers to access array elements:

The name of the output array alone is equivalent to the address of the first element of the output array ! = The name of the array represents the address of the first element of the array


int a[10]={1,2,3,,4,5,6,7,8,9,10};
int *p;//先声明指针变量
p=&a[0]//然后将指针赋予地址

This writing is equivalent to:

int a[10]={1,2,3,,4,5,6,7,8,9,10};
int *p;//先声明指针变量
p=a;//然后将指针赋予首元素地址

Easier:

int a[10]={1,2,3,,4,5,6,7,8,9,10};
int *p=a;//一步代替两步,声明并赋值地址


*(p+i) represents the i-th unit behind p (each unit is the small square in the picture above)!


The following [ ] is an operator , used to take the value in the array


a represents the first address of the array, i represents the i-th unit after the last address, and d represents the number of bytes occupied by each unit (that is, the number of bytes occupied by each small box)!


Methods for referencing array elements:

example:

The suggested method at the bottom is the standard use of pointers to access the array a[10]

It represents the definition of the pointer variable *p, and assigns the address of the first element of the array a to p. In this case, p represents the address of the first element of a, and then p<(a+10) represents the 10 elements after the loop a, The output value is *p to point to the value in a[];

#include <stdio.h>
int main()
{
    int a[10]={1,2,3,4,5,6,7,8,9,10};
    int *p;
    for(p=a;p<(a+10);p++)//p++代表指向a[]的下一个单元,也就是顺着之后的地址依次读取
    {
       printf("%d ",*p);
    }
    return 0;
}

or:

#include <stdio.h>
int main()
{
    int a[10]={1,2,3,4,5,6,7,8,9,10};
    int *p;
    p=a;//首元素地址赋值
    while(p<a+10)
    {
       printf("%d ",*p++);//根据运算的优先级,先是取值再加加
    }
    return 0;
}






Experience:


Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=324063065&siteId=291194637