Thread: recursive 2D arrays

  1. #1

    recursive 2D arrays

    Consider the recursive function header:

    void matrixfunc( int a[5][5])

    I would like to be able to pass the array a with the dimension constants 5 and 5 as variables rather than constants, similiar to:

    void matrixfunc( int a[size]a[size] )

    where size will be change within matrixfunc itself. the line of code size = size - 1 will occur somewhere within the function in order to decrease the size of the array.

    Is there some kind of fix that allows me to pass 2 D arrays without the size of the array being a constant.

    Ultimately, I would like to use void matrixfunc( int a[][]) in my recursion, but I know already that i am unable to do this.

  2. #2
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    >Is there some kind of fix that allows me to pass 2 D arrays
    >without the size of the array being a constant.
    Yes, you can pass the array as a pointer to a pointer and define the size for the compiler manually in the function. You *really* don't want to do this though, take my word for it. The best option in this case would be to wrap the array in a struct and pass the struct. That way you don't have to worry about the size of the array while avoiding the freaky notation of passing multidimensional arrays.

    My best code is written with the delete key.

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    The edge of the known universe
    I'm assuming that the initial call to this function will always start with arrays of the same size.
    #define SIZE 5
    void foo ( int arr[SIZE][SIZE], int size ) {
        int r, c;
        if ( size == 0 ) return;
        for ( r = 0 ; r < size ; r++ ) {
            for ( c = 0 ; c < size ; c++ ) {
                foo( arr, size-1 );
    int main() {
        int a[SIZE][SIZE];
        foo( a, SIZE );
        return 0;
    Each recursive call to foo 'removes' the last row and last column from being processed.
    The array is passed as a pointer, so all you're doing is just using less of the memory you're pointing at each time around.

    If you want to shrink the array to some corner other than [0][0], then that's easy enough to achieve with a few extra parameters to define the effective bounds of the array.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Help with 2d arrays
    By thamiz in forum C Programming
    Replies: 25
    Last Post: 05-25-2008, 05:06 AM
  2. 2D Array's, assigning chars.
    By gman89 in forum C Programming
    Replies: 9
    Last Post: 04-26-2008, 11:03 PM
  3. returning 2D arrays
    By ... in forum C++ Programming
    Replies: 2
    Last Post: 09-02-2003, 12:28 PM
  4. Initialising 2D and 3D arrays
    By fry in forum C++ Programming
    Replies: 5
    Last Post: 08-01-2002, 04:34 AM
  5. Reading 2d arrays from file?
    By Ringhawk in forum C++ Programming
    Replies: 3
    Last Post: 01-17-2002, 09:05 PM