您的位置:首页 > 其它

Pointer and Array--some code fragment

2011-06-23 11:01 513 查看

Dereference Yields an Lvalue

*sp = "goodbye"; // contents of s now changed
string s2 = "some value";
sp = &s2; // sp now points to s2

Subscripts and Pointers

int ia[] = {0,2,4,6,8};
int i = ia[0]; // ia points to the first element in ia
int *p = &ia[2]; // ok: p points to the element indexed by 2
int j = p[1]; // ok: p[1] equivalent to *(p + 1),
// p[1] is the same element as ia[3]
int k = p[-2]; // ok: p[-2] is the same element as ia[0]

Using Pointers to Access Array Elements

int ia[] = {0,2,4,6,8};
int *ip = ia; // ip points to ia[0]
ip = &ia[4]; // ip points to last element in ia
ip = ia; // ok: ip points to ia[0]
int *ip2 = ip + 4; // ok: ip2 points to ia[4], the last element in ia
// error: ia has only
4000
4 elements, ia + 10 is an invalid address
int *ip3 = ia + 10;
ptrdiff_t n = ip2 - ip; // ok: distance between the pointers
int last = *(ia + 4); // ok: initializes last to 8, the value of ia[4]
last = *ia + 4; // ok: last = 4, equivalent to ia[0]+4

Pointer to pointer

int ival = 1024;
int *pi = &ival; // pi points to an int
int **ppi = π // ppi points to a pointer to int
int *pi2 = *ppi; // ppi points to a pointer
cout << "The value of ival/n"
<< "direct value: " << ival << "/n"
<< "indirect value: " << *pi << "/n"
<< "doubly indirect value: " << **ppi
<< endl;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息