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

作者:@渔阳俊俊
本文为作者原创,转载请注明出处:https://www.cnblogs.com/wjq13752525588/p/15948033.html


        指针和数组基本等价的原因在于指针算数(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。结果是,指针也指向了数组中下一个元素。

 

posted @   渔阳俊俊  阅读(56)  评论(0编辑  收藏  举报
编辑推荐:
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· 写一个简单的SQL生成工具
· AI 智能体引爆开源社区「GitHub 热点速览」
点击右上角即可分享
微信分享提示