C++指针、数组和指针算数
2022/3/6 14:50:49
本文主要是介绍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。结果是,指针也指向了数组中下一个元素。
这篇关于C++指针、数组和指针算数的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-10-07fastcgi 是什么-icode9专业技术文章分享
- 2024-10-07fastcgi 的详细使用教程介绍-icode9专业技术文章分享
- 2024-10-07git如何更新单个文件到本地-icode9专业技术文章分享
- 2024-10-07如何使用ASM(Abstract Syntax Tree Manipulation)技术来修改第三方AAR依赖中的函数-icode9专业技术文章分享
- 2024-10-07Activity 跳转时间耗时很长怎么优化解决-icode9专业技术文章分享
- 2024-10-07Androud Toast 有哪些常用的第三方组件-icode9专业技术文章分享
- 2024-10-07在viewmodel中怎么使用 mmkv?-icode9专业技术文章分享
- 2024-10-07MMKV.defaultMMKV() 是单例模式吗?-icode9专业技术文章分享
- 2024-10-04el-table 开启定时器下,表格的选中状态会消失是什么原因-icode9专业技术文章分享
- 2024-10-03如何安装和初始化飞牛私有云 fnOS?-icode9专业技术文章分享