7-变量内存单元地址

变量存储在哪里

变量内存单元地址

代码实现

#include <iostream>
using namespace std;

int main() {
	int n;
	float f;
	double d = 1.23; // 0.0
	char c = '*';
	cout << "address of n: " << &n << endl;
	cout << "address of f: " << &f << endl;
	cout << "address of d: " << &d << endl;
	cout << "address of c: " << &c << endl; // 这行的结果很奇怪!
	// & : 取得变量内存单元地址的“操作符”!
	return 0;
}

运行结果

image

代码实现

#include <iostream>
using namespace std;

int main() {
	int n;
	float f;
	double d = 0.0; // 0.0
	char c = '*';
	cout << "address of n: " << &n << endl;
	cout << "address of f: " << &f << endl;
	cout << "address of d: " << &d << endl;
	cout << "address of c: " << &c << endl; // 这行的结果很奇怪!
	// & : 取得变量内存单元地址的“操作符”!
	return 0;
}

运行结果

image

含义

  • &是一个运算符,功能是“取变量的地址”,所以&n会返回变量n的内存单元地址
  • 对于内存单元地址,count会自动以16进制形式输出地址值。在这种形式输出结果中,前2个字符固定为0x或0X
  • 在输出字符变量的内存地址时,cout采取另外的特殊处理方式——不是输出字符变量的内存单元地址,而是输出内存单元存储的字符内容,且将相邻的后续内存单元以字符形式输出出来,直至碰到一个内容为0的内存单元才停止

内存图解

image

posted @ 2022-11-20 21:21  彩红caihong  阅读(36)  评论(0)    收藏  举报