【C++ Primer Plus学习记录】指针——指针算术

指针和数组基本等价的原因在于指针算术和C++内部处理数组的方式。

将整数变量加1后,其值将增加1;但将指针变量加1后,增加的量等于它指向的类型的字节数。例如:将指向double的指针加1后,如果系统对double使用8个字节存储,则数值将增加8;将指向short的指针加1后,如果系统对short使用2个字节存储,则指针值将增加2。

//4.19
#include
using namespace std;

int main()
{
	double wages[3] = { 10000.0, 20000.0, 30000.0 };
	short stacks[3] = { 3, 2, 1 };

	//获得数组地址的两种方法
	double *pw = wages;//name of an array = address
	short *ps = &stacks[0];//or use address operator

	cout << "pw = " << pw << ",*pw = " << *pw << endl;
	pw = pw + 1;
	cout << "add 1 to the pw pointer:\n";
	cout << "pw = " << pw << ",*pw = " << *pw << endl << endl;

	cout << "ps = " << ps << ",*ps = " << *ps << endl;
	ps = ps + 1;
	cout << "add 1 to the ps pointer:\n";
	cout << "ps = " << ps << ",*ps = " << *ps << endl << endl;

	cout << "access two elements with array notation\n";
	cout << "stacks[0] = " << stacks[0] << ",stacks[1] = " << stacks[1] << endl;
	cout << "access two elements with pointer notation\n";
	cout << "*stacks = " << *stacks << ",*(stacks + 1) = " << *(stacks + 1) << endl << endl;

	cout << sizeof(wages) << " = size of wages array\n";//对数组应用sizeof运算符得到的是数组的长度
	cout << sizeof(pw) << " = size of wages array\n";//对指针应用sizeof运算符得到的是指针的长度

	system("pause");
	return 0;
}

总之,使用new来创建数组以及使用指针来访问不同的元素很简单,只需要把指针当作数组名对待即可。

你可能感兴趣的:(c++,学习,开发语言)