CS253

CS253: Software Development with C++

Spring 2018

Pointers

See this page as a slide show

Pointers

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: In function 'int main()':
c.cc:3:5: error: invalid conversion from 'int*' to 'int'
c.cc:4:5: 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: In function 'int main()':
c.cc:3:6: 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: In function 'int main()':
c.cc:3:2: error: increment of read-only variable 'p'

Modified: 2018-01-23T17:14

User: Guest

Check: HTML CSS
Edit History Source
Apply to CSU | Contact CSU | Disclaimer | Equal Opportunity
Colorado State University, Fort Collins, CO 80523 USA
© 2015 Colorado State University
CS Building