Professional Documents
Culture Documents
xPtr x
Pointing to Arrays
• Pointers can also point to arrays.
• For example:
int x[5] = {2,4,6,8,10};
int *xPtr = NULL;
• When you declare x, the operating system will
allocate space for you array:
– Each element in the array will take up 4 bytes of memory
(see previous slides.) The operating system therefore needs
to allocate (5 elements * 4 bytes = 20 bytes of memory.)
– Let’s assume that the operating system finds space at
memory location 100.
Pointing to Arrays
• The x array in memory:
Array
Indexes
[0] [1] [2] [3] [4]
Values 2 4 6 8 10
Physical
Addresses 100 104 108 112 116
2 4 6 8 10
xPtr
100 104 108 112 116
• The value of xPtr is now: 100
• The value of *xPtr is now: 2
Pointing to Arrays
• Now we have the following code:
xPtr = &x[4]
xPtr will now point to element #4 in the array
2 4 6 8 10
xPtr
100 104 108 112 116
• The value of xPtr is now: 116
• The value of *xPtr is now: 10
Pointing to Arrays
• Shortcut: an array name is an alias for the address
of the 0th element in the array.
xPtr = x;
is the same as: xPtr = &x[0]
2 4 6 8 10
xPtr
100 104 108 112 116
Pointer Arithmetic
• Once you have a pointer, you can apply a number
of arithmetic operators to it:
++ Increment
-- Decrement
+ Plus
- Minus
• Suppose you have xPtr pointing to element 0 of an
array, and then suppose you want to print each
element in the array:
– You can use pointer arithmetic to do this!
Pointer Arithmetic
• Pointer Arithmetic is not the same as regular arithmetic.
• For example, suppose we have the following code:
int x = 5;
x++;
int i;
int x[5] = {45, 55, 65, 75, 85};
for (i=0; i<5; i++) {
printf (“%d\t”, x[i]);
}
Pointers and Arrays
• Option 2: Pointer / Offset Notation
– in this option, we use our knowledge of pointer arithmetic to
achieve the same goal.
int offset = 0;
int x[5] = {45, 55, 65, 75, 85};
int *xPtr = NULL;
/* point to zeroeth element to start */
xPtr = &x;
/* use pointer / offset noation */
for (offset = 0; offset < 5; offset++) {
printf (“%d\t”, *(xPtr + offset));
}
Example: Pointers and Arrays
Example
• Let’s examine a concrete example.
• The goal of the program is to copy the contents of
one array to another array.
• The program has two functions:
– copy1: uses array notation
– copy2: uses pointer / offset notation
– they both achieve the same goal.
#include <stdio.h>
main () {
char string1[MAXCHARS], string3[MAXCHARS];
char string2 [MAXCHARS] = "Hello";
char string4 [MAXCHARS] = "Good Bye";
Hello Hello
Good Bye Good Bye