Pointers and Arrays: Lesson 1
Pointers and Arrays: Lesson 1
Lesson 1
Pointers
• What is a pointer
o A variable whose value is the
address of another variable P 11 23
o p is a pointer to variable v
• Operations
o &: address of (reference)
o *: indirection (dereference) v 1000 11
• Declaration mimics use
o int *p;
p is the address of an int
(dereference p is an integer)
0
o int v;
p = &v;
p stores the address of v
Pointer Operation Examples
• Examples of * and &
int x, y, *p;
p = &x; /* p gets the address of x */
y = *p; /* y gets the value point to by p
*/
y = *(&x); /* same as y = x */
• Unary operators associate right to
left
y = *&x; /* same as y = *(&x) */
• Unary operators bind more tightly
than binary ones
y = *p + 1; /* same as y = (*p) + 1; */
y = *p++; /* same as y = *(p++); */
More Pointer Examples
• References (e.g., *p) are
variables
int x, y, *px, *py;
px = &x; /* px is the address ofx
*/
*px = 0; /* sets x to 0 */
py = px; /* py also points tox */
*py += 1; /* increments x to 1 */
y = (*px)++; /* sets y to 1, x to 2
*/
• What about the following?
++*px
*px++
Argument Passing
• C functions pass arguments “by value”
• To pass arguments “by reference,” use pointers
X 3 X 7 X X
y 7 y 3 y y
a 3 a 7 a 3 a 7
b 7 b 3 b 7 b 3
Pointers and Arrays
• Pointers can “walk along” arrays
int a[10], *p, x;
P=a; /* p gets the address of a[0] */
p = &a[0]; /* p gets the address of a[0] */
x = *p; /* x gets a[0] */
x = *(p+1); /* x gets a[1] */
p = p + 1; /* p points to a[1] */
p++; /* p points to a[2] */
• What about the following?
x = *p++;
x = ++*p;
Pointers and Arrays, cont’d
• Array names are constant pointers
int a[10], *p, i;
p = a; /* p points to a[0] */
a++; /* Illegal; can’t change a constant */
p++; /* Legal; p is a variable */
• Subscripting is defined in terms of pointers
a[i], *(a+i), i[a] /* Legal and the same */
&a[i], a+i /* Legal and the same */
p = &a[0] /* &*(a+0) &*a a */
• Pointers can walk arrays efficiently
p = a;
for (i = 0; i < 10; i++)
Cout<< *p++ ;
Pointer Arithmetic
• Pointer arithmetic takes into account the stride
(size of) the
value pointed to
long *p;
p += i; /* increments p by i elements */
p -= i; /* decrements p by i elements */
p++; /* increments p by 1 element */
p--; /* decrements p by 1 element */
• If p and q are pointers to same type T
p – q /* number of elements between p and q */
• Does it make sense to add two pointers?
Pointer Arithmetic, cont’d
• Comparison operations for pointers
o <, >, <=, >=, ==, !=
o if (p < q) ... ;
o p and q must point to the same array
o no runtime checks to ensure this
• An example
int strlen(char *s) {
char *p;
for (p = s; *p; p++)
;
return p – s;
}
Pointer & Array Parameters
• Equivalence example
void f(int *a[10]);
void f(int **a);
• Another equivalance example
void g(int a[][10]);
void g(int (*a)[10]);
• Legal in both f and g:
**a = 1;
Command-Line Arguments