CS253: Software Development with C++

Spring 2018

Pointers

See this page as a slide show

CS253 Pointers

Pointers

An example

int a[] = {11, 22, 33, 44, 55};
int *p = &a[2];
cout << *p << '\n';
p += 2;
cout << *p << '\n';
33
55

A bad example

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'

Declaration style

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;

Another example

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

References

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

A common use

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

Use of const

DeclarationExplanation
int *anon-const pointer to non-const ints
const int *bnon-const pointer to const ints
int *const cconst pointer to non-const ints
const int *const dconst pointer to const ints
int &e = …reference a non-const int
const int &f = …reference to a const int

Examples

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'

Examples

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'

User: Guest

Check: HTML CSS
Edit History Source

Modified: 2018-04-24T16:55

Apply to CSU | Contact CSU | Disclaimer | Equal Opportunity
Colorado State University, Fort Collins, CO 80523 USA
© 2018 Colorado State University
CS Building