• 指针运算


    #define _CRT_SECURE_NO_WARNINGS
    #include<stdio.h>
    #include<string.h>
    #include<stdlib.h>
    #include<math.h>
    #include<time.h>

    //数组

    void my_strcpy01(char*dest,char*ch)

    {

      int i=0;

    //当i读到0时,为假,则不执行

      while(ch[i]!='')

      {

        dest[i]=ch[i];

        i++;

      }

      dest[i]=0;

    }

    //指针+偏移量

    void my_strcpy02(char*dest,char*ch)

    {

      int i=0;

      while(*(ch+i))

      {

        *(dest+i)=*(ch+i);

        i++;

      }

      *(dest+i)=0;

    }

    //纯指针

    void my_strcpy03(char*dest,char*ch)

    {

      while(*ch)

      {

        *dest=*ch;

    //指针+1相当于指向数组下一个元素,内存地址变化了sizeof(char)

        dest++;

        ch++;

      }

      *dest=0;

    }

    //最简

    void my_strcpy(char*dest,char*ch)

    {

    //1、*ch取值,*dest   2、*dest=*ch   3、条件判断(直到0=0,为假,则不执行)   4、ch++;dest++

      while(*dest++=*ch++);

    }

    int main01()

    {

    //字符串拷贝

      char ch[]="hello world";

      char dest[100];

      

      my_strcpy(dest,ch);

      printf("%s ",dest);

      return EXIT_SUCCESS;

    }

    int main02(void)

    {

      int arr[]={1,2,3,4,5,6,7,8,9,10};

      int*p=arr;

      char*q;

      //arr[-1]//err数组下标越界

      p=&arr[3];

      

    //指针操作数组时,下标允许是负数

      printf("%d ",p[-2]);//同*(p-2)=2

    //内存地址相差12/sizeof(int)=偏移量=3

      int step=p-arr;

      printf("%d ",step);//3

    //指针的加减运算和指针的类型有关

    //内存地址相差12

      printf("%p ",p);

      printf("%p ",arr);

    //内存地址相等

      p--;

      p--;

      p--;

      printf("%p ",p);

      pirntf("%p ",arr);

    //指针的加减运算和指针的类型有关

      q=&arr[3];

    //因为这里是char类型,所以这里是地址每次-1,而不是减4

      q--;

      q--;

      q--;

    //内存地址相差9

      printf("%p ",q); //0077F945

      printf("%p ",arr);//0077F93C

      return 0;

    }

    int main(void)

    {

    //指针和运算符的操作

      int arr[]={1,2,3,4,5,6,7,8,9,10};

      int*p=arr;

      p=&arr[3];

    //野指针;乘除取余相加不能;但能加减偏移量,减法能减指针

      //p = p + arr;//err

      //p = p * arr;//err
      //p = p / arr;//err
      //p = p % 4;//err

    //两个指针允许做大小比较,逻辑运算符等

    }

  • 相关阅读:
    Balance的数学思想构造辅助函数
    1663. Smallest String With A Given Numeric Value (M)
    1680. Concatenation of Consecutive Binary Numbers (M)
    1631. Path With Minimum Effort (M)
    1437. Check If All 1's Are at Least Length K Places Away (E)
    1329. Sort the Matrix Diagonally (M)
    1657. Determine if Two Strings Are Close (M)
    1673. Find the Most Competitive Subsequence (M)
    1641. Count Sorted Vowel Strings (M)
    1679. Max Number of K-Sum Pairs (M)
  • 原文地址:https://www.cnblogs.com/wanghong19991213/p/13550589.html
Copyright © 2020-2023  润新知