Raluca Damaris Lupeş
Raluca Damaris Lupeş

Reputation: 11

Two-dimensional array type errors

Basically, in the code below I have a function which initialises a two-dimensional array. In the main function I try to test the function with different sizes of the array. However, I get the following errors: "error: array type has incomplete element type void chessBoard(char board[][], int length, int width)" and "error: type of formal parameter 1 is incomplete". chessBoard(board1, length1, width1);. ANy suggestions?

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

    void chessBoard(char board[][], int length, int width)
    {
      for (int i = 0; i < length; i++)
      { 
        for (int j = 0; j < width; j++)
          if ((i + j) % 2 == 0)
            board[i][j] = 'b';
          else 
            board[i][j] = 'w';
      }
    }

    int main()
    {
      char board1 [3][4];
      int length1 = sizeof board1 / sizeof board1[0];
      int width1 = sizeof board1[0] / sizeof(int);
      chessBoard(board1, length1, width1);
      int i, j;
      for(i = 0; i < length1; i++)
      {
        for(j = 0; j < width1; j++)
          printf("%c", board1[i][j]);

        printf("\n");
      }
      printf("\n");
}

Upvotes: 0

Views: 311

Answers (2)

Prosen Ghosh
Prosen Ghosh

Reputation: 655

you can also declare your function like this.void chessBoard(char board[][width], int length). int widthis global variable.

#include <stdio.h>
#include <stdlib.h>
int width;//Global Variable
void chessBoard(char board[][width], int length){
    int i,j;
    for ( i = 0; i < length; i++){
        for ( j = 0; j < width; j++){
            if ((i + j) % 2 == 0)
                board[i][j] = 'b';
            else
                board[i][j] = 'w';
        }//inner loop end
    }//outer loop end
}
int main(){
    char board1[3][4];
    int length1 = sizeof(board1) / sizeof(board1[0]);
    int width1 = sizeof(board1[0]) / sizeof(board1[0][0]);
    width = width1;
    chessBoard(board1, length1);
    int i, j;
    for(i = 0; i < length1; i++){
        for(j = 0; j < width1; j++)
            printf("%c ", board1[i][j]);
            printf("\n");
    }
    printf("\n");
}

Upvotes: 0

prophet1906
prophet1906

Reputation: 123

You should declare your function like this:

void chessBoard(char board[][4], int length, int width)

This C FAQ thoroughly explains why. The gist of it is that arrays decay into pointers once, it doesn't happen recursively. An array of arrays decays into a pointer to an array, not into a pointer to a pointer. According to the C standard, you can pass any dimensional array to functions as long as you specify all the dimensions as constants except first one (which can be blank).

Upvotes: 1

Related Questions