数组下标:
==========
类型: size_t
==========
使用示例:
const size_t array_size = 10;
int ia[array_size];
for (size_t ix = 0; ix != array_size; ++ix)
ia[ix] = ix;
指针:
==========
最典型使用:
string s("hello world");
string *sp = &s; // sp holds the address of s
==========
初始化:
如果不知应该怎样初始化指针比较好,则可以先将指针初始化为 0。
常用方法:
#include <cstdlib>
int *pi = NULL; // 相当于0
==========
void* 指针:可以保存任何类型对象的地址:
double obj = 3.14;
double *pd = &obj;
void *pv = &obj;
pv = pd;
==========
使用指针访问数组元素:在表达式中使用数组名
int ia[] = {0,2,4,6,8};
int *ip = ia; // ip points to ia[0]
==========
指针运算:
int *ip2 = ip + 3; 计算结果:指针
int *ip2 = ip - 3; 计算结果:指针
注意:这里+n/-n中的n都是整数,不同于容器(如vector)中迭代器的要求(容器中要求必须为size_type类型)
ptrdiff_t n = ip2 - ip; 计算结果:ptrdiff_t类型
注意:ptrdiff_t 来自cstddef头文件
==========
遍历数组:可以用于数组的迭代器,来遍历数组。
const size_t arr_sz = 5;
int int_arr[arr_sz] = { 0, 1, 2, 3, 4 };
for (int *pbegin = int_arr, *pend = int_arr + arr_sz; pbegin != pend; ++pbegin) {
cout << *pbegin << ' ';
*pbegin = 0;
}
==========
指向const对象的指针与const指针的区别:
指向const对象的指针:
const double *cptr;
*cptr = 42; // error: *cptr might be const
const指针:
int errNumb = 0;
int *const curErr = &errNumb;
==========
指针和 typedef:
typedef string *pstring;
const pstring cstr;
请问 cstr 变量是什么类型?
string *const cstr;
而不是const string *cstr;