// ios::exceptions
#include <iostream>
using namespace std;
int main ()
{
//只要指针指向数组元素,就可以对它进行下标操作.
char c[6] = "hello";
char * pc = &c[2];
cout << "*pc:" << *pc << endl;
cout << "*pc[-2]:" << pc[-2] << endl; //这里等价于c[0]
cout << "c:" << reinterpret_cast<long>(c) << endl; //这里要用long,用int会报精度丢失的错误
char *pcEnd = c + sizeof(c)/sizeof(char); //数组末尾后的一个元素位置,可以类比迭代器的end()
cout << "pcEnd:" << reinterpret_cast<long>(pcEnd) << endl;
cout << "pcEnd - c: " << pcEnd - c << endl;
//模拟用迭代器遍历数组的操作
for(char * pcIter = c; pcIter != pcEnd; pcIter++)
{
cout << *pcIter << ' '; //cout也可以打印字符.
}
return 0;
}
打印结果:
*pc:l
*pc[-2]:h
c:140734689135746
pcEnd:140734689135752
pcEnd - c: 6
h e l l o