Passing 2d char array to function

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

The point of this code is to read the puzzle in words, and then find the words in this puzzle. I am going to write a function to do a direct search, search on search terms, and then search up and down.

How to get rid of this error? The error is 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); } 
+7
source share
2 answers

It's a little difficult to get what you want to do, but there is a problem:

 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 rows, int cols, int array[rows][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(ROWS, COLS, x); } 
+5
source

You need to call directly

  forward(words, puzzle); 

However, you have an error in your code: you forgot j++ in the read loop while reading words , so you overwrite words[0] and do not initialize other members of the array.

Also, in a real situation, you may need to choose the size of the array at runtime. An easy way to do this is to choose a large enough limit for the width and height and go with the 0x90 solution (you need a 30x20 puzzle, and you can easily handle it since you compiled with ROWS and COLS equal to, say, 1024).

A more complicated way would be to use malloc() (using pointers to pointers to characters) and dynamically allocate both arrays, limited by available memory; you then pass your measurements to the forward function.

 int forward(char **words, char **puzzle, size_t w_w, size_t w_h, size_t p_w, size_t p_h) { } 

However, the allocation part will be more complicated given the malloc() calls in cycles and the need to check its return value each time to catch the conditions of lack of memory; also in some scenarios you may want to free up memory (for example, to run repetitive puzzles), which will lead to further complexity.

+3
source

All Articles