Concepts of Programming Languages

(Sean Pound) #1
9.5 Parameter-Passing Methods 411

parameter, the formal parameter must include the number of columns in the
second pair of brackets. This is illustrated in the following skeletal C program:


void fun(int matrix[][10]) {


... }
void main() {
int mat[5][10];
...
fun(mat);
...
}


The problem with this method of passing matrixes as parameters is that it
does not allow a programmer to write a function that can accept matrixes with
different numbers of columns; a new function must be written for every matrix
with a different number of columns. This, in effect, disallows writing flexible
functions that may be effectively reusable if the functions deal with multidi-
mensional arrays. In C and C++, there is a way around the problem because of
their inclusion of pointer arithmetic. The matrix can be passed as a pointer, and
the actual dimensions of the matrix also can be passed as parameters. Then, the
function can evaluate the user-written storage-mapping function using pointer
arithmetic each time an element of the matrix must be referenced. For example,
consider the following function prototype:


void fun(float *mat_ptr,
int num_rows,
int num_cols);


The following statement can be used to move the value of the variable x
to the [row][col] element of the parameter matrix in fun:


(mat_ptr + (row num_cols) + col) = x;


Although this works, it is obviously difficult to read, and because of its com-
plexity, it is error prone. The difficulty with reading this can be alleviated by
using a macro to define the storage-mapping function, such as


#define mat_ptr(r,c) (mat_ptr + ((r)
(num_cols) + (c)))


With this, the assignment can be written as


mat_ptr(row,col) = x;


Other languages use different approaches to dealing with the problem of
passing multidimensional arrays. Ada compilers are able to determine the defined

Free download pdf