appropriately分配内存地址

本文介绍C++中变量的内存地址分配原理,详细解释了如何使用地址运算符(&)获取变量的内存地址,并引入指针的概念及其声明方式。
当这个statement is executed by the CPU,RAM存储器from a piece of将被撤销。为了……的利益的例子,让我们说the变量x is assigned记忆租赁140。当the program变量x in the年看见金声明表达,它知道它应该的样子在记忆租赁140 to get the value。
尼斯的事关于变量是我们不需要担心什么特定的内存地址是分配。我们只是refer to the given by its变量的确定,and the编译translates this name into the appropriately分配内存地址。
However,this approach has some局限,which我们讨论in this和未来的教训。
the address - of算子(&)

the address - of算子(&)允许美国to see what is assigned to a内存地址的变量。这是很直接的。

1
2
3
4
5
6
7
8
9
10
#include <iostream>
 
int main()
{
    int x = 5;
    std::cout << x << '\n'; // print the value of variable x
    std::cout << &x << '\n'; // print the memory address of variable x
 
    return 0;
}

在作者的机器上,上面的程序打印出来:

0027fea0

注:虽然解引用操作符看起来就像乘法运算符,你可以区分它们,因为取消引用运算符是一元的,而乘法运算符是二元。
指针
用运算符和引用运算符的地址添加到我们的工具,我们现在可以谈的指针。指针是一个变量,它保存一个内存地址作为它的值。
指针通常被视为一个最令人困惑的部分的C++语言,但他们是出奇的简单,合理的解释。
声明一个指针
指针变量的声明就像普通的变量,只有数据类型和变量名之间的星号:

1
2
3
4
5
6
7
int *iPtr; // a pointer to an integer value
double *dPtr; // a pointer to a double value
 
int* iPtr2; // also valid syntax (acceptable, but not favored)
int * iPtr3; // also valid syntax (but don't do this)
 
int *iPtr4, *iPtr5; // declare two pointers to integer variables


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值