6. Pointer Arrays; Pointers to Pointers
 
6.1 Pointer
 
Address stored by pointer also data in memory
Can address location of address in memory – pointer to that pointer
 
int n= 3;
int ∗pn =&n;            /∗ pointer to n ∗/
int ∗∗ppn =&pn;       /∗ pointer to address of n ∗/
 
Many uses in C: pointer arrays, string arrays
 
Example: What does the difference?
void swap( int ∗∗a, int ∗∗b)
{
     int ∗temp = ∗a;
     ∗a = ∗b;
     ∗b = temp ;
}
 
void swap(int *a, int *b)
{
     int temp;
     temp = *a;
     *a = *b;
     *b = temp;
}
 
6.2 Pointer Arrays
 
Pointer array – array of pointers
 
int ∗arr[20]; // an array of pointers to int’s char
∗arr[10];      // an array of pointers to char’s
 
Pointers in array can point to arrays themselves
 
char ∗strs [10]; // an array of char arrays (or strings)
 
Example
– Compute the sorted array from the int arr[100].
– Can declare a pointer array int ∗sorted_array[100]; containing pointers to elements of arr and sort    the pointers instead of the numbers themselves
/∗ iterate until out−of−order element found; shift the element, and continue iterating ∗/
void insertion_sort(void)
{
    unsigned int i, len = array_length(arr);

    for (i=1; i<len; i++) {
        if (∗sorted_array[i] < ∗sorted_array[i−1])
           shift_element(i);
}

/∗ move previous elements down until insertion point reached ∗/
void shift_element(unsigned int i)
{
    int ∗pvalue ;

    /∗ guard against going outside array ∗/
    for (pvalue = sorted_array[i];
        i && ∗sorted_array[i−1] > ∗pvalue; i−−) {
        /∗ move pointer down ∗/
        sorted_array[i] = sorted_array[i−1];
    }

    sorted_array[i] = pvalue; /∗ insert pointer ∗/
}
 
6.3 String Arrays
 
An array of strings, each stored as a pointer to an array of chars
Each string may be of different length
 
char str1[] = "hello" ;      /∗ length = 6 ∗/
char str2[] = "goodbye" ; /∗ length = 8 ∗/
char str3[] = "ciao" ;       /∗ length = 5 ∗/
char strArray[] = {str1, str2, str3};
 
– Note that strArray contains only pointers, not the characters themselves!
 
 
 
 
이전페이지 / 7 / 다음페이지