c++复习【学习日常】【指针】【小白向】【大佬轻点喷】

#c++小白由于上课没好好听 :innocent: :innocent: :innocent:寒假复习了一下指针

  1. 复习了指针常量和常量指针

     int a = 10;
     int b = 20;
    //常量指针,可修改指针的指向,不能修改指向的值
     const int* p1 = &a;
     p1 = &b;
    //指针常量,可修改指针指向的值
     int* const p2 = &a;
     *p2 = 20;
     //p2 = 20;(这个是错的)
    

然后就疑惑这个*什么时候要取什么时候不要取
https://blog.csdn.net/yuechifanfan/article/details/111588978
根据这个老哥的分析,得出了结论:
大概率当不加就是指针变量本身存储的值,加上代表指针变量指向的值

  1. 复习了指针的自增(用指针遍历数组,不知道有什么用,先学着再说)

    //用指针遍历数组
    int arr[10] = { 1,2,3,4,5,6,7,8,9,10 };
    int* p = arr;
    for(int i=0;i<10;i++)
    {
     cout << *p << endl;
     p++;
    }
    
  2. 复习了值传递和地址传递

    void swap01(int a, int b)
     {
       int temp = a;
       a = b;
       b = temp;
       cout << "a="<< a << " " <<"b=" << b << endl;
      }
    void swap02(int* p1, int* p2)
    {
     int temp = *p1;
    *p1 = *p2;
    *p2 = temp;
    cout << "a=" << *p1 << " " << "b=" << *p2 << endl;
    }
       int a = 10;
       int b = 20;
    //值传递
     swap01(a, b);
     cout << "a=" << a << " " << "b=" << b << endl;
     cout << endl;
    //地址传递	
     swap02(&a, &b);
    cout << "a=" << a << " " << "b=" << b << endl;
    
1 个赞

要多理解本质,有条件的话看看指针在汇编代码中的结果。指针可以理解为地址,从这个地址取值即是*