Académique Documents
Professionnel Documents
Culture Documents
CS1 - Pointers 1
Pointers
A pointer is a variable
MEMORY
that holds the Address
address of 0
1
something else. 2
int foo; foo 3 123
int *x; 4
5
...
...
foo = 123;
x = &foo; x 81345 3
81346
81347
CS1 - Pointers 2
int *x;
• x is a pointer to an integer.
• You can use the integer x-points-to in a
C++ expression like this:
“the int x points to”
y = *x + 17;
*x = *x +1;
CS1 - Pointers 3
&foo
In C++ you can get the address of a
variable with the “&” operator.
MEMORY
int foo; Address
0
1
foo = 123; 2
x = &foo; foo 3 123
4
5
...
...
&foo means “the address of foo”
CS1 - Pointers 4
Assigning a value to a
dereferenced pointer
A pointer must have a value before you
can dereference it (follow the pointer).
int *x; int foo;
*x=3; int *x;
x = &foo;
ing!!!
OR !!! o anyth *x=3;
ERR n’t point t
s
x doe is fine
this to foo
po ints
x
CS1 - Pointers 5
Pointers to anything
x some int
int *x;
int **y; y some *int some int
CS1 - Pointers 6
Pointers and Arrays
• An array name is basically a const
pointer.
• You can use the [] operator with a
pointer:
int a[5];
CS1 - Pointers 8
printing an array
void print_array(int a[], int len) {
for (int i=0;i<len;i++) n
rsio
cout << "[" << i << "] = " ve
ray
<< a[i] << endl; ar
}
CS1 - Pointers 9
Passing pointers as
parameters
void swap( int *x, int *y) {
int tmp;
tmp = *x;
*x = *y;
*y = tmp;
}
CS1 - Pointers 10
Pointer Parameters
• Pointers are passed by value (the value
of a pointer is the address it holds).
CS1 - Pointers 12
String Manipulation Functions
• C++ includes a library of C string
handling functions:
lots more!
CS1 - Pointers 13
String Example - Count the
chars
int count_string( char *s) {
p ointed
int n=0; the thing
wh ile ull
is no t n
while (*s) { to by s
n++; increment count
s++;
set s to point to the next char
}
return(n);
}
CS1 - Pointers 14
Another way
int count_string( char *s) {
char *ptr = s;
while (*ptr) {
ptr++;
pointer arithmetic!
}
return(ptr - s);
}
CS1 - Pointers 15
C String vs. C++ string
class
• C++ string class is much easier to use
– comparison operator, concatenation
operator, no memory allocation issues...