美文网首页
C++ 指针

C++ 指针

作者: 小潤澤 | 来源:发表于2020-03-16 19:54 被阅读0次

    指针简介

    指针的作用是可以通过指针间接访问内存
    每创建一个变量,都对应着一个地址编号,我们获取这个变量的内容,可以通过访问其地址来实现,那么指针就是用于保存地址的


    指针定义

    我们如下定义指针

    #include<iostream>
    using namespace std;
    
    int main(){
     //定义指针
      int a = 10;
     //定义指针语法,数据类型+*+指针变量名
      int * p;
     //让指针记录变量a的地址,&取地址符
      p = &a;
      cout<<"a的地址为: "<<&a<<end1;
      ##此时打印出16进制的地址
      cout<<"指针p为: "<<p<<end1;
    
    //使用指针,*p可以修改a的内容(读和写)
      *p = 1000;
      cout<<"a= "<<a<<end1;
      cout<<"*p= "<<*p<<end1;
    
    
     system("pause");
      return 0;
    }
    

    我们通过*p来对a变量的内容进行修改,所以a输出为1000,而不是10

    那么指针变量指向内存编号为0的空间称为0指针

    #include<iostream>
    using namespace std;
    
    int main(){
      //空指针
      int *p = NILL;
    
    system("pause");
      return 0;
    }
    

    空指针不能进行访问

    野指针是指对某个指针指定地址,但是不能对其进行访问(没有申请地址)

    #include<iostream>
    using namespace std;
    
    int main(){
      //野指针
      int *p = (int *)0x1100;
      cout<<*p<<end1;
      system("pause");
      return 0;
    }
    

    修饰指针const,被修饰的指针或者常量就不可以进行修改

    #include<iostream>
    using namespace std;
    
    int main(){
      //1.修饰指针
      int a = 10;
      const int *p = &a;
      *p = 20;//报错
    
      //2.修饰常量
       int * const p = &a;
       *p = 200;
    
      //3. 修饰指针常量
       const int * const p = &a;
       *p = 200;//报错
     
     system("pause");
      return 0;
    }
    

    指针数组

    #include<iostream>
    using namespace std;
    
    int main(){
     
      int arr[10] = {1,2,3,4,5,6,7,8,9,10 };
      //访问第一个元素
      int *p = arr;
      cout<<"第一个元素: "<<*p<<end1;
    p++;
      cout<<"第二个元素: "<<*p<<end1;
    
    //遍历所有元素
      int *p2 = arr;
      for (int i = 0; i < 10;i++)
     {
          cout<<*p2<<end1;
          p2++;
     }
    
     system("pause");
      return 0;
    }
    

    指针函数

    #include<iostream>
    using namespace std;
    
    void swap01(int a, int b)
     {
         int temp = a;
         a = b;
         b = temp;
     }
    
    void swap02(int *p1, int *p2 )
     {
         int temp = *p1;
         *p1 = *p2;
         *p2 = temp;
     }
    
    int main(){
       
      int a = 10;
      int b = 20;
      swap01(a , b);
      cout<<"a= "<<a<<end1;
      cout<<"b= "<<b<<end1;
    
      swap02(&a,&b);
      cout<<"a= "<<a<<end1;
      cout<<"b= "<<b<<end1;
    
    system("pause");
      return 0;
    }
    

    地址传递可以改变实参数值,其原理是内存地址发生了改变

    若不想改变实参,采用值传递,若想改变曾用地址传递

    相关文章

      网友评论

          本文标题:C++ 指针

          本文链接:https://www.haomeiwen.com/subject/plnfshtx.html