-3

I wrote this to perform floodfill and here are two issues: 1-i need to get length from user,how can I pass an array with unknown length to a function? 2-should I change arguments which recall floodfill inside the function?

#include <stdio.h>

int main() {
    const int length = 9;
    int board[length][length],sheet[length][length];
    int i=1,j=1;
    floodfill(board,sheet,i,j);
    return 0;
}

void floodfill(int board[length][length],int sheet[length][length], int i,int j){

    if(board[i][j]!=-1)
    {
        sheet[i][j]= 1;
        if(i-1>0 && j>0)
            floodfill(board, sheet, i-1,j);
        if(i+1>0 && j>0)
            floodfill(board, sheet, i+1,j);
        if(i>0 && j+1>0)
            floodfill(board, sheet, i,j+1);
        if(i>0 && j-1>0)
            floodfill(board, sheet, i,j-1);
    }
}
I'mDoneOK
  • 39
  • 2
  • 9

1 Answers1

0

how can I pass an array with unknown length to a function?

If your compiler supports variable length arrays (VLA), which is true for most modern compilers because the C99 standard required it and in the current (C11) standard, they are an optional feature, you can pass it like this:

void example(size_t rows, size_t cols, int array[][cols])

So, you pass first the dimensions, then the (pointer to the) array while referring to the earlier parameters. Note that you have to give all dimensions except for the first one.

Of course, if both dimensions are the same, you only need one parameter for them, like in your case:

void example(size_t length, int array[][length])

If you can't use VLAs because your compiler indeed lacks support, your best bet is to use a flat array instead (of size rows * cols here) and calculate the indices. With a function like this:

void example(size_t rows, size_t cols, int *array)

you would have to dynamically allocate your array in your main code, e.g. like this:

int *array = malloc(rows * cols * sizeof *array);

and then you would access the elements manually, e.g. if you want index [i][j], you'd write:

array[i * cols + j]