int a[] = {11, 22, 33, 44, 55}; int *p = &a[2]; cout << *p << '\n'; p += 2; cout << *p << '\n';
33 55
a
is an array of int
s
a[2]
is an int
&a[2]
is an int *
, or the address of an int
p
is an int *
, or a pointer to an int
*p
is an int
int a[] = {11, 22, 33, 44, 55}; int *p = &a[2], n; n = p; p = n;
c.cc:3: error: invalid conversion from 'int*' to 'int'
These are all equivalent, since spaces matter little:
int *a; int* b; int*c; int * d;
However, consider this. What types are e
and f
?
int* e, f;
That’s why I do this:
int *g, h;
int a[] = {11, 22, 33, 44, 55}; int *p = a; cout << *p << '\n'; *p += 8; cout << *p << '\n'; p += 2; cout << *p << '\n';
11 19 33
a
is an array of int
s
a
is equivalent to &a[0]
A reference is like a pointer, with auto-indirection.
int a[] = {11, 22, 33, 44, 55}; int &r = a[2]; cout << r << '\n'; r += 2; cout << r << '\n';
33 35
void f1(string s) { // call by value cout << s << '\n'; } void f2(const string &s) { // call by const reference cout << s << '\n'; } int main() { string filename = "/etc/group"; f1(filename); f2(filename); return 0; }
/etc/group /etc/group
const
so that f2
can’t change the argument.
const
Declaration | Explanation |
---|---|
int *a | non-const pointer to non-const int s |
const int *b | non-const pointer to const int s |
int *const c | const pointer to non-const int s |
const int *const d | const pointer to const int s |
int &e = … | reference a non-const int |
const int &f = … | reference to a const int |
Declare a pointer to constant integers. We can change the pointer, but not the integers.
int alpha[] = {11,22,33,44,55}; const int *p = alpha; p += 2; cout << *p;
33
int beta[] = {11,22,33,44,55}; const int *p = beta; *p = 42;
c.cc:3: error: assignment of read-only location '* p'
Declare a constant pointer to integers. We can change the the integers, but not the pointer.
int gamma[] = {11,22,33,44,55}; int *const p = gamma; *p = 42; cout << *p;
42
int delta[] = {11,22,33,44,55}; int *const p = delta; p++;
c.cc:3: error: increment of read-only variable 'p'