编程语言
首页 > 编程语言> > C++指针、数组和指针算数

C++指针、数组和指针算数

作者:互联网

        指针和数组基本等价的原因在于指针算数(pointer arithmetic)和C++内部处理数组的方式。首先,我们来看一看算术。将整数变量加1后,其值将增加1;但将指针变量加1后,增加的量等于它指向的类型字节数。将指向double的指针加1后,如果系统对double使用8个字节存储,则数值将增加8;将指向short的指针加1后,如果系统对short使用2个字节存储,则指针将增加2。

 

#include <iostream>
int main()
{
using namespace std;
double wages[3] = { 10000.0, 20000.0, 30000.0 };
short stacks[3] = { 3, 2, 1 };

//Here are two ways to get the address of an array
double* pw = wages;
short* ps = &stacks[0];
//with array element
cout << "pw = " << pw << ", *pw = " << *pw << endl;
pw = pw + 1;
cout << "add 1 to the pw pointer:\n";
cout << "pw = " << pw << ", *pw = " << *pw << "\n\n";
ps = ps + 1;
cout << "add 1 to the pw pointer:\n";
cout << "ps = " << ps << ", *ps = " << *ps << "\n\n";

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;

cout << sizeof(wages) << " = size of wages array\n";
cout << sizeof(pw) << " = size of pw pointer\n";
return 0;
}

输出结果:

pw = 0076FCF4, *pw = 10000
add 1 to the pw pointer:
pw = 0076FCFC, *pw = 20000

add 1 to the pw pointer:
ps = 0076FCE6, *ps = 2

access two elements with array notation
stacks[0] = 3, stacks[1] = 2
access two elements with pointer notation
*stacks = 3, *(stacks + 1) = 2
24 = size of wages array
4 = size of pw pointer

 

  程序说明

  在多数情况下,C++将数组名解释为数组第一个元素的地址。因此,下面的语句将pw声明为指向double类型的指针,然后将它初始化为wages----wages数组中第一个元素的地址:

  double * pw = wages;

  和所有数组一样,wages也存在下面的等式:

  wages = &wages[0] = address of first element of array

  为表明情况确实如此,该程序在表达式&stacks[0]中显式地使用地址运算符来将ps指针初始化为stacks数组中的第一个元素。

  接下来,程序查看pw和*pw的值。前者是地址,后者是存储在该地址中的值。由于pw指向第一个元素,因此*pw显示的值为第一个元素的值,即10000。接着,程序将pw加1。正如前面指出的,这样数字地址值将增加8,这使得pw的值为第二个元素的地址。因此,*pw现在的值是20000——第二个元素的值。

 

 

   此后,程序对ps执行相同的操作。这一次由于ps指向的是short类型,而short占用2个字节,因此将指针加1时,其值将增加2。结果是,指针也指向了数组中下一个元素。

 

标签:ps,cout,C++,算数,wages,指针,stacks,pw
来源: https://www.cnblogs.com/wjq13752525588/p/15948033.html