zoukankan      html  css  js  c++  java
  • [C++] C++指针的那些事 常量,变量,指针及指针相关的三个数值

    常量: 只有数据, 虽然也占用存储空间, 但在编译后的代码中只引用数据,没有地址的概念.如:

    const string hi = "hello";

    const int days = 31;

    变量: 存储在内存里的数据(右值), 修改时需要引用地址(左值). 如:

    int  num = 12;

    float d = 354.333F;

    bool b = true;

    而指针则要关注3个数值: 存储指针变量的内存地址, 指针指向的内存地址, 指针指向的值.

    若定义一个指针变量:  

    int num = 8;

     int p*= #

    则这三个数值则分别表示为: &p, p, *p.

    如下示例:

     int main()
     {
    	int *p=NULL;
    
    	cout<<"初始化后未赋值:"<<endl;
    	cout<<"指针变量地址(&p) = "<<&p<<endl;
    	cout<<"指针指向的地址(p) = "<<p<<endl;
    	if (p!=NULL)
    		cout<<"指针指向地址存储的值(*p) = "<<*p<<endl;
    	else
    		cout<<"空指针, 不能取值."<<endl;
    	
    	p= new int(1024);
    
    	cout<<"赋值后:"<<endl;
    	cout<<"指针变量地址(&p) = "<<&p<<endl;
    	cout<<"指针指向的地址(p) = "<<p<<endl;
    	if (p!=NULL)
    		cout<<"指针指向地址存储的值(*p) = "<<*p<<endl;
    	else
    		cout<<"空指针, 不能取值."<<endl;
    
    	delete p;
    	p = NULL;
    
    	cout<<"释放后:"<<endl;
    	cout<<"指针变量地址(&p) = "<<&p<<endl;
    	cout<<"指针指向的地址(p) = "<<p<<endl;
    		if (p!=NULL)
    		cout<<"指针指向地址存储的值(*p) = "<<*p<<endl;
    	else
    		cout<<"空指针, 不能取值."<<endl;
                   return 0;
    }
    

     弄明白这三者的关系与区别, 就可以很清楚的理解指针了.

     特别提示: 定义指针时最好赋值先NULL, 而释放指针时(delete) 则最好也赋值 NULL, 这样就可以避免一些错误的指针动作.

    ~做事情贵在坚持~
  • 相关阅读:
    Bluedroid介绍
    Android蓝牙介绍
    Android Bluetooth抓包
    Bluetooth LMP介绍
    Bluetooth Baseband介绍
    Bluetooth SDP介绍
    Bluetooth HFP介绍
    Bluetooth RFCOMM介绍
    Bluetooth L2CAP介绍
    Windows开发
  • 原文地址:https://www.cnblogs.com/csMapx/p/2290125.html
Copyright © 2011-2022 走看看