C++内存与指针

1 int year;   year = 1000; (内存地址在0028ff44)
2 
3 int *  ptr_year;      // int * 即声明了一个指针型变量,指针是一个变量,保存的是一个变量的地址。
4 
5                                      // 在声明语句中,可以把 " * " 看作是指针的类型
6 
7  ptr_year = &year    // &取变量的地址,即ptr_year == 0028ff44;

 

 

而在非声明语句中,* ptr_year是指抄老底,直接对此指针指向的变量进行更改

1 int * ptr_year;       //声明语句
2 
3 * ptr_year = 1001     //非声明语句 ,相当于year = 1001
4 
5  

指针初始化:

nullptr(寄存器常量)

  • 初始方法1        int * ptr1 = nullptr     //相当于int * ptr1 = 0
  • 初始方法2        int * ptr2 = 0
  •  

void * ptr   :特殊类型的指针类型,它可以存放任意对象的地址。

 

指针还可以加减,如数组中,

 1 #include <iostream>
 2 
 3 using namespace std;
 4 int main()
 5 {   double int_v[3] = {1,10,1000};//英文符号是红色,中文是粉色!
 6     double *ptr;
 7      ptr = &int_v[0];
 8      ptr += 1;
 9     cout << *ptr << endl;  // 输出 10
10 
11 }

 

数组名其实就是数组首元素的地址,int_v = &int_v[0]    // 数组名其实就是指向数组首元素的指针

因此第i+1个元素的地址可以表示为:int_v[i]或   int_v  +  i 

 

 

引用(&):实质是指针功能的封装。

 1 #include <iostream>
 2 #include <vector>
 3 #include <algorithm>
 4 
 5 using namespace std;
 6 int main()
 7 {  int int_value = 1000;
 8 
 9     int& refvalue = int_value;    //引用就是对指针的简单封装而已,减少了星号的使用次数。
10     refvalue = 999;       //对引用的赋值根本还是通过指针找到地址给予更改。
11     cout << int_value << endl;
12     //指向常量的引用是非法的如:int& refvalue  = 10   
13     const int& refvalue2 = 10;//合法,const是真的意思,真常量。const定义的变量也是真常量,否则为变量。
14     //如 const int i =2; 则i为常量。
15     //int i = 2;i为变量。
16 }
17  

 

posted @ 2019-08-26 17:22  Parallax  阅读(112)  评论(0编辑  收藏  举报