C++学习第四天

1. 存储变量值的内存

/*
- 指针是一个变量,与所有变量一样,指针也占用内存空间

- 指针的特殊之处在于,指针包含的值(这里为0x558)被解读为内存地址,因此指针是一种指向内存单元的特殊变量

- 引用运算符(&)也叫地址运算符
*/

#include <iostream>
using namespace std;


int main(){
    int age = 30;
    const double pi = 3.1416;

    // use & to get the address of a variable
    // 作为一种约定,显示十六进制数时,应加上文本0x
    cout << "Integer age is at: 0x" << &age << endl;
    cout << "Double pi is located at: 0x" << hex << &pi << endl;


    return 0;
}

2. 声明并初始化指针

#include <iostream>
using namespace std;


int main(){
    int age = 40;
    int* pointer = &age; // pointer to an int, initialized to &age

    // displaying the value of pointer
    cout << "Integer age is at: 0x" << hex << pointer << endl;


    return 0;
}

3.引用运算符

/*这个程序表明,同一个int指针(pInteger)可指向任何int变量*/
#include <iostream>
using namespace std;


int main(){
    int age = 30;
    int* pointer = &age; //pointer stores the address of age
    
    cout << "pointer points to age now" << endl;

    // displaying the value of pointer
    cout << "pointer = 0x" << hex << pointer << endl;

    int dogs_age = 9;
    pointer = &dogs_age; //pointer now points to dogs_age
    cout << "pointer now points to dogs_age" << endl;

    cout << "pointer = 0x" << hex << pointer << endl;

    return 0;
}

4. 解除引用运算符

/*解除引用运算符(*)也叫间接运算符*/
#include <iostream>
using namespace std;


int main(){
    int age = 18;
    int dogs_age = 3;

    int* pointer = &age;
    cout << "pointer points to age" << endl;
    cout << "*pointer = " << *pointer << endl;

    pointer = &dogs_age;
    cout << "pointer points to dogs_age now" << endl;
    cout << "*pointer = " << *pointer << endl;

    int* pointer_1 = &dogs_age;
    cout << "Enter an age for your dog: ";
    cin >> *pointer_1;

    cout << "Your dog is " << *pointer_1 << " years old." << endl;


    return 0;
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值