指针的算术运算

一, 了解指针的算术运算:

    #include "stdio.h"
    int main()
    {
        int arr[] = { 1,2,3,4,5,6,7,8,9,10 };
        int *p = arr;
        *p = 10;
        p++;//指针加1:加一个单元格(从arr[0]到arr[1])
        *p = 20;
        printf("%d\n", arr[1] );
    
        double brr[5] = { 122.5,34.5,56.7 };
        double *dp = brr;
        dp++;//指针加1:加一个单元格
        *dp = 100;
        printf("%f\n", brr[1] );
    
    
        char crr[5] = "abc";
        char *cp = crr;
        cp++;//指针加1:加一个单元格
        *cp = 'v';
        printf("%c\n", crr[1] );
        
        return 0;
    
    }

程序运行结果如下:
指针的算术运算_第1张图片

(1),指针+数字

#include 

int main()
{
    int *p=(int *)2000;
    printf("%d\n",p-2);//2000-2*sizeof(int)=1992,int 4个字节
    printf("%d\n",(char)*p-2);//2000-2*sizeof(char)=1998,char 1 个字节
    printf("%d\n",(short)*p-2);//2000-2*sizeof(short)=1996,short 2个字节
    printf("%d\n",(long long*)p-2);//1984,long 8个字节
    printf("%d\n",(float*)p-2);//1992,float 4个字节
    printf("%d\n",(double*)p-2);//1984,double 8个字节
    printf("%d\n",(int**)p-2);//2000-2*sizeof(int*)=1992,去掉一个*,是指针,指针为4个字节
    printf("%d\n",(unsigned long)p-2);//1998  没*,不是指针
    return 0;
}

(2),指针-数字

int main()
{
    int *p = (int *)0x2010;
    printf("%x\n",p-2);  //"%x"以十六进制格式输出,0x2010-8=0x2008
    printf("%x\n",(short *)p-2);  //200c
    printf("%x\n",(unsigned long *)p-2);  //2008
    printf("%x\n",(long long **)p-2);  //2008
    printf("%x\n",(float *)p-2);  //2008
    printf("%x\n",(double *)p-2);  //2000
    printf("%x\n",(char *)p-2);  //200e
    printf("%x\n",(unsigned long )p-2);  //200e
    
    return 0;
}

(3),指针-指针

意义:表示间隔的单元格数,可正可负,先算出间隔的字节,然后除以sizeof(指针本身)

int main()
{
    int arr[10] = {1};
    int *p = &arr[1];
    int *q = &arr[9];
    printf("%d\n",p-q);  //-8
    printf("%d\n",q-p);  //8
    printf("%d\n",(short *)q-(short *)p);
    // int型4个字节,p、q间隔4*8=32个字节,short型占2个字节,32/2=16

    printf("%d\n",(double *)q-(double *)p);  //4
    printf("%d\n",(int ***)q-(int ***)p);  //8
    printf("%d\n",(char **)q-(char **)p);  //8
    printf("%d\n",(long)q-(long)p);  //32
    
    return 0;
}

总结:
指针的算术运算+,-
1,指针+i,表示加i个单元格,其加isizeof(指针本身去掉一个)字节
2,指针-i,表示减i个单元格,其减isizeof(指针本身去掉一个)字节
3,指针+指针,非法
4,指针-指针:表示间隔的单元格数,可正可负,先算出间隔的字节,然后除以sizeof(指针本身)

二,【】自带解引用

(1)int *p;

     p=arr;

    //p[i]==*(p+i)

(2)int *p;

     p=&arr[3];

     p[-1];//==*(p-1)==arr[2]

     //*(arr+i)==arr[i]

应用:

void Mystrcpy1(char *des,char *src)
{
    int i;
    for(i=0;src[i]!='\0';i++)
    {
        des[i] = src[i]; //没有可见的*解引用,但[]自带解引用
    }
    des[i] = '\0';
}

//下标换成指针
void Mystrcpy2(char *des,char *src)
{
   int i;
    for(i=0;*(src+i)!='\0';i++)
    {
        *(des+i)=*(src+i);
    }
    *(des+i)='\0';
}

void Mystrcpy3(char *des,char *src)
{
    while(*des++=*src++);
}

int main()
{

    char arr[10];
    char brr[10] = "abcd";
    Mystrcpy(arr,brr);
    printf("arr=%s\n",arr);
    return 0;

}

你可能感兴趣的:(指针的算术运算)