Expert C Programming

(Jeff_L) #1

Play Around with Array/Pointer Arguments


Write and execute a program to convince yourself that the preceding information is true.



  1. Define a function that takes a character array ca as an argument. Inside the
    function, print out the values of &ca and &(ca[0]) and &(ca[1]).

  2. Define another function that takes a character pointer pa as an argument.
    Inside the function, print out the values of &pa and &(pa[0]) and
    &(pa[1]) and ++pa.

  3. Set up a global character array ga and initialize it with the letters of the
    alphabet. Call the two functions using this global as the parameter. Compare
    the values that you print out.

  4. In the main routine, print out the values of &ga and &(ga[0]) and
    &(ga[1]).

  5. Before running your program, write down which values you expect to match,
    and why. Account for any discrepancies between your expected answers and
    observed results.


It takes some discipline to keep all this straight! Our preference is always to define the parameter as a
pointer, since that is what the compiler rewrites it to. It's questionable programming style to name
something in a way that wrongly represents what it is. But on the other hand, some people feel that:


int table[] (^) instead of int *table
explains your intentions a bit better. The notation table[] makes plain that there are several more
int elements following the one that table points to, suggesting that the function will process them all.
Note that there is one thing that you can do with a pointer that you cannot do with an array name:
change its value. Array names are not modifiable l-values; their value cannot be altered. See Figure 9-4
(the functions have been placed side by side for comparison; they are all part of the same file).
Figure 9-4 Valid Operations on Arrays that are Arguments


pointer argument array argument pointer non-argument


int array[100],


array2[100];


fun1(int *ptr) fun2(int arr[]) main()


{ { {


ptr[1]=3; arr[1]=3; array[1]=3;


ptr = 3; arr = 3; *array = 3;

Free download pdf