1

So we're learning how to use dynamic arrays with malloc and such and I'm basically going nuts on trying to learn how to use this thing. At the surface on what I'm trying to do is have a user enter a crossword puzzle and have the program solve it but I can't even get through the first step of successfully storing the puzzle.

Heres my code:

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

int main (){

    char *userInput = malloc (sizeof(char)*4);
    // allocates columns with a length of 4?
    char **grid = malloc(sizeof(char)*4);
    int i, j;

    for(i=0; i<4; i++){
        scanf("%s", userInput);
        for (j=0; j<4; j++){
            // allocates rows with a length of 4?
            grid[i] = (char*) malloc (sizeof(char)*4);
            grid[i][j] = userInput[j];
        }
    }

    printf("%c", grid[0][2]);

    return 0;
}

Its hard coded now but it'll ask the size of the grid but what its doing is taking a 4x4 crossword puzzle and putting each letter into a character array and later on it'll find the words in the puzzle. All I'm trying to do right now is take the user input and put it into a grid. A sample on what I'm trying to do with my code is

Input:
abcd
efgh
ijkl
mnop

Output:
c

but what ends up being spit out is garbage.

I'm using code blocks but when I debug malloc arrays and I set them to 'watch' I have no idea whats in them. It shows me where they are in memory but I have no idea whats inputted in them so I can't even check whats going on. Any help would be appreciated.

Yitzak Hernandez
  • 355
  • 4
  • 23

1 Answers1

1

It's a good idea to separate the allocation of the array from the filling of the array. Trying to do both at once can get confusing. To allocate the array, you need to allocate 4 character pointers, and then each pointer needs to point to 4 bytes of memory.

int rows = 4;
int cols = 4;

char **grid = malloc( rows * sizeof(char *) );  // 4 char pointers, one for each row
for ( int i = 0; i < rows; i++ )
    grid[i] = malloc( cols );                   // each row is 4 characters
user3386109
  • 34,287
  • 7
  • 49
  • 68