【第四章】 复合类型---4.8 指针、数组和指针算术

时间:2023-01-07 15:34:40
/* programNo4.19 */
/***********************************
2017年9月29日15:18:41
Athor:xiyuan255
Course:C++
Contain:addpntrs.cpp
Reference: C++ Primer plus
知识点:
1.指针算术:将整数变量加1后,其值将增加1;但将指针变量加1后,
增加的量等于它指向的类型的字节数(如指向int类型,如果系统对
int使用4个字节,则数值增加4)。
2.C++将数组名也解释为地址。所以array[i]与array[i+1]的地址相差
了数组元素数据类型的字节数个字节。
3.arrayname[i] becomes *(arrayname + i)
编译器实际上是将arrayname[i]解析为*(arrayname + i)进行操作的
所以这两则实际上是等价的;
4.指针与数组名的区别:
(1) 指针可以修改其值,而数组名却是常量;(实际上数组名是一个确
定的地址,当他定义完数组时,数组名在内存中就指代该内存区域的首
地址;为一确定值,而指针不同,它声明的一块内存区域,只是该内存
区域里面只存放指针类型的变量,即地址,至于存放什么地址,可以程
序员自己按需要修改。)
pointername = pointername + 1; // valid
arrayname = arrayname + 1; // not allowed
(2) 对数组应用sizeof运算符得到的数组长度,而对指针应用运算符sizeof
得到的是指针的长度,即使此时指针指向的是一个数组。
*************************************/
// addpntrs.cpp -- pointer addition

#include <iostream>

int main(void)
{
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; // name of an array = address
short * ps = &stacks[0]; // or use address operator
// 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 << endl;

cout << "ps = " << ps << ", *ps = " << *ps << endl;
ps = ps + 1;
cout << "add 1 to the ps pointer: \n";
cout << "ps = " << ps << ", *ps = " << *ps << 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;

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

return 0;
}

/**
输出结果:
pw = 0034FBFC, *pw = 10000
add 1 to the pw pointer:
pw = 0034FC04, *pw = 20000
ps = 0034FBEC, *ps = 3
add 1 to the ps pointer:
ps = 0034FBEE, *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.
*/