-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);
    }
}
2
  • Does this compile? Commented Nov 23, 2017 at 18:48
  • @FelixPalmen nope Commented Nov 23, 2017 at 19:01

1 Answer 1

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]
Sign up to request clarification or add additional context in comments.

4 Comments

so converting it to vector can solve it?
Uhmmm ... what?
1d array = vector
There's no "vector" in C. But there's a reason I wrote this as the second part. If you can assume VLA support (you already use it in the code of your question), use the syntax from the first part of my answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.