henryfoster03
henryfoster03

Reputation: 3

Passing Arrays in functions in C

I have this code, which is simulating Conway's game(not really important what that is for this question), and I was just wondering how to pass my array, board, to my function neighbor. I keep getting a compiler error saying that I have an incomplete element type in the function declaration, even though I was told I needed to put the empty square brackets there to pass functions, and it doesn't work without the square brackets. If anyone could help here to pass the function, that would be very helpful. Here is my code:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

struct info
{
    int red;
    int blue;
};

struct info neighbor(char board[][], int, int);

int main(int argc, char* argv[])
{
    if(argc != 3)
    {
        printf("usage: dimensions repititions\n");
        return 1;
    }
    srand(time(NULL));
    int games = 0;
    int d = atoi(argv[0]);
    int repititions = atoi(argv[1]);
    //create board
    char board [d][d];
    for(int i = 0; i < d; i++)
    {
        for(int j = 0; j < d; j++)
        {
            int choice = rand() % 100;
            if(choice < 44)
            {
                if(choice % 2 == 0)
                {
                    board[i][j] = '#';
                }
                else
                {
                    board[i][j] = '*';
                }
            }
            else
            {
                board[i][j] = '.';
            }
        }
    }
    while(games < repititions)
    {
        for(int i = 0; i < d; i++)
        {
            for(int j = 0; j < d; j++)
            {
                neighbor(board, i, j);
            }
        }
    }

}

struct info neighbor(char board, int i, int j)
{
    char grid [3][3];
    for(int u = 0; u < 3; u++)
    {
        for(int v = 0; v < 3; v++)
        {
            grid[u][v] = board[i][j];
            i ++;
        }
        j++;
    }
}

Upvotes: 0

Views: 51

Answers (2)

dbush
dbush

Reputation: 225352

When passing a multidimensional array to a function, the size of all dimensions except the first must be specified. When such an array is variable length, the declaration should look like this:

struct info neighbor(int, int, char board[*][*]);

And the definition would look like this:

struct info neighbor(int i, int j, char board[i][j]) {

Upvotes: 1

ApuchYz
ApuchYz

Reputation: 3

In that case you need to pass the number of columns in function parameter that is initializing 2D array.

struct info neighbor(char board[][number_of_columns], int, int);

struct info neighbor(char board[][number_of_columns], int i, int j)

Upvotes: 0

Related Questions