Passing 2-D Arrays of unknown size ?

michael k finegan mfinegan at uceng.UC.EDU
Thu Dec 21 01:21:35 AEST 1989


    While I think the answer is no, I'll ask anyway! :-)

    Is there a method for passing/using multi-D arrays in subroutines,
without specifying the column (fastest changing) dimension in advance ? No way
to set the column length dynamically ? Any more elegant alternatives ?
For example:

main()
{
    char array1[25][25], array2[50*50];

   /* inefficient way if several differently sized arrays */
    solution_func1(array1,25,25);
   /* elegant, but doesn't work ! */
    solution_func2(array1,25,25);	/* array1 could be ?alloc'ed ... */
   /* less then elegant, especially if long calculations inside [] */
    solution_func3(array2,50,50);
}

/* create separate function for every different size array ? */
solution_func1(array,rows,cols)
char array[][MUST BE SPECIFIED as 25 !];   /* could use cols in FORTRAN!     */
int rows, cols;				   /* and I don't even like FORTRAN! */
{
    int i,j;

    for(i ...)
        for(j ...)
            some_operation(array[i][j]);
}

solution_func2(array,rows,cols)
char **array;
int rows, cols;
{
    int i,j;

    for(i ...)
        for(j ...)
	   /* Only works for argv ? (argv special?),
	    * or compiler uses '\0' to sense last col in 2-D char arrays ?
 	    * No way to let compiler know sizes ?
 	    */
            some_operation(array[i][j]);
}

solution_func3(array,rows,cols)
char *array;
int rows, cols;
{
    int i,j;

   /* But now I can't use array[][] notation,
    * and must calculate the indices myself !
    */
    for(i ...)
        for(j ...)
            some_operation(array[i*cols + j]);

   /* with typically: array[(long calculated value)*stride*cols +
    *					stride*(another calculated value)]
    */
}


	Any ideas/examples appreciated! Maybe C++ allows overloading of
[] symbols ?
				Mike Finegan
				mfinegan at uceng.UC.EDU



More information about the Comp.lang.c mailing list