码迷,mamicode.com
首页 > 编程语言 > 详细

C++ 指针 * 和 引用 &

时间:2019-04-21 10:10:38      阅读:185      评论:0      收藏:0      [点我收藏+]

标签:绑定   str   color   clu   简单   目标变量   简单的   stream   enc   

指针

先看一个简单的例子:

#include <iostream>
using namespace std;

int main() {
    // your code goes here
    int num = 123;
    int* p = &num;
    cout<<"p:"<<p<<endl;
    cout<<"*p:"<<*p<<endl;
    cout<<"num:"<<num<<endl;
    cout<<"&num:"<<&num<<endl;
    return 0;
}

运行结果:

p:0x7ffc2861549c
*p:123
num:123
&num:0x7ffc2861549c

p是指向num地址的指针,所以p的值为num的地址。可以给*p赋值,此时num值也会发生相应的变化,但是不会因此而改变p所指向的地址。

#include <iostream>
using namespace std;

int main() {
    int num = 123;
    int* p = &num; // 这里&为取址
    cout<<"*p = "<<*p<<endl;
    cout<<"p = "<<p<<endl;
    
    *p = NULL;
    cout<<"*p = "<<*p<<endl;
    cout<<"p = "<<p<<endl;
    cout<<"num = "<<num<<endl;
}

*p = 123
p = 0x7ffccb7a153c
*p = 0
p = 0x7ffccb7a153c
num = 0

引用

C++引用

类型标识符 &引用名=目标变量名

#include <iostream>
using namespace std;

int main() {
    int num1 = 1, num2 = 2;
    int &ref1 = num1, &ref2 = num2; ///引用必须要初始化
    cout<<"num1 = "<<num1<<",num2 = "<<num2<<endl;
    cout<<"ref1 = "<<ref1<<",ref2 = "<<ref2<<endl;
    ///修改引用的值将改变其所绑定的变量的值
    ref1 = -1;
    cout<<"num1 = "<<num1<<",ref1 = "<<ref1<<endl;
    
    ///将引用b赋值给引用a将改变引用a所绑定的变量的值,
    ///引用一但初始化(绑定),将始终绑定到同一个特定对象上,无法绑定到另一个对象上
    ref1 = ref2;
    cout<<"num1 = "<<num1<<",ref1 = "<<ref1<<endl;
    return 0;
}

num1 = 1,num2 = 2
ref1 = 1,ref2 = 2
num1 = -1,ref1 = -1
num1 = 2,ref1 = 2

指向指针的指针

#include <iostream>
using namespace std;

int main() {
    int val = 1;
    int *p1 = &val;
    int **p2 = &p1;///**声明一个指向指针的指针
    cout<<"val = "<<val<<endl;
    cout<<"p1 = "<<p1<<", *p1 = "<<*p1<<endl;
    cout<<"p2 = "<<p2<<", *p2 = "<<*p2<<",**p2 = "<<**p2<<endl;
    return 0;
}

val = 1
p1 = 0x7ffe520c3d34, *p1 = 1
p2 = 0x7ffe520c3d38, *p2 = 0x7ffe520c3d34,**p2 = 1

指针与数组

#include <iostream>
using namespace std;

int main() {
    int arr[5][5];
    arr[2][1] = 666;
    cout<<*(*(arr + 2) + 1)<<endl;
    return 0;
}
#include <iostream>
using namespace std;

int main() {
    int arr[100];
    for (int i = 0; i < 100; i++)
        arr[i] = i;
    int *p = arr;  //等价于int *p = &arr[0];
    //数组的变量名就是一个指针
    cout<<"p = "<<p<<",*p = "<<*p<<endl;  //p = 0x7ffe3b44b8b0,*p = 0
    
    int t = 100;
    while (t--)
        ///可以直接对指针进行加减运算,就和迭代器一样
        cout<<*(p++)<<endl;  //输出0~99
        
    ///指针可以做差:
    int *p2 = &arr[10], *p3 = &arr[20];
    cout<<"p2 - p3 = "<<(p2 - p3)<<endl;  //p2 - p3 = -10
    
    ///还可以比比较大小:
    cout<<(p2 < p3 ? p3 - p2 : p2 - p3)<<endl; //10
    return 0;
}

 

C++ 指针 * 和 引用 &

标签:绑定   str   color   clu   简单   目标变量   简单的   stream   enc   

原文地址:https://www.cnblogs.com/KresnikShi/p/10743638.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!