hatfieldac hatfieldac - 1 month ago 7
C Question

Passing 2d array char into function

I'm trying to pass a 2D array with strings in it into a function. I keep getting the
expected expression before ] token.

The point of this code is to read in a wordsearch puzzle, then find the words in that puzzle. I'm going to be writing a function for forward search, backword search, and then up and down search.

How do I get rid of this error? The error is down at the very bottom where I call the forward function.

/*Andrea Hatfield CPE 101 October 31st, 2012*/
#include <stdio.h>
#include <string.h>

int forward(char words[][8], char puzzle[][11]);


int main()
{
char puzzle[11][11];
char words[8][8];
FILE *fin, *fwords;
int i = 0;
int j= 0;

fin = fopen("puzzle.in", "r");
fwords = fopen("words.in", "r");


if(fin == NULL) /*Reads in the puzzle file*/
printf("File does not exist");
else
{
while(fscanf(fin,"%s", puzzle[i])!=EOF)
{
printf("%s\n", puzzle[i]);
i++;
}


}

if(fwords == NULL) /*Reads in the words the puzzle will search for */
printf("File does not exist");
else
{
while(fscanf(fwords, "%s", words[j])!=EOF)
{
printf("%s\n", words[j]);
}
}


forward(&words[][8], &puzzle[][11]); /*Error at this point*/
return(0);
}

Answer

It is a little bit hard to get what you want to do but there is a problem in here:

forward(&words[][8], &puzzle[][11]);

try this instead:

forward(words, puzzle);

Here are two other options that should be mentioned from here:

#define ROWS 4
#define COLS 5

void func(int array[ROWS][COLS]) {
  int i, j;

  for (i=0; i<ROWS; i++) {
    for (j=0; j<COLS; j++) {
      array[i][j] = i*j;
    }
  }
}

void func_vla(int array[rows][cols], int rows, int cols) {
  int i, j;

  for (i=0; i<rows; i++) {
    for (j=0; j<cols; j++) {
      array[i][j] = i*j;
    }
  }
}

int main() {
  int x[ROWS][COLS];

  func(x);
  func_vla(x, rows, cols);
}
Comments