1
votes
    void display_grid(struct game_board *M, FILE *stream) {
        int i, j;

        /* malloc memory for appropriate amount of rows */
        M->border = malloc(sizeof(*M->border) * (M->width + 4));


        for (i = 0; i <= M->width; i+=2){
            M->border[i] = M->border[M->width + 1] = '+';
            for (j = 1; j <= M->width; j+=2){
                M->border[j] = M->border[M->width] = ' ';
                fprintf(stream, "%c\n", M->border[i][j]);
            }
        }
        M->border[M->width + 2] = '\0';

        fflush(stream);
   }

My question is in regards to this line fprintf(stream, "%c\n", M->border[i][j]); which shoots an error and stops the overall program from compiling.

At the moment I am simply trying to read in the height and width from what the user is providing from the command line and using that to print out a 2D grid that I can then use later on to modify and such.

I have a solution which I THINK might fix it but I have no idea on how to implement it. I believe that in order to fix the problem I need to malloc border as a ** and then malloc the rows as *

1
Wait... How many elements does border have? It looks as if you construct it with width+4, but try to read it as if it were width(width+1). - Beta
Alright, I might've fixed something. I had originally declared border as a char * inside of a struct at the start of the program. In my understanding, this would in turn mean that I had declared a 1D array. But by changing the declaration of border to char **, I have now declared it as a 2D array. Would this be accurate? - burnsieXD
You seem to have a misconception of how arrays work. The short answer is that declaring a pointer and constructing an array are very different things. The longer answer is that I urge you to play around with arrays in isolation (i.e. not as part of a structure or a complex project) until you can handle 1D or 2D (or higher) with ease, then incorporate them into other code. - Beta
char **a is no 2D array! Setup and usage is more complicated than using a proper 2D array. I agree with @Beta. You really should first learn to walk before starting to run. - too honest for this site
what's the definition of struct game_board? - Arlie Stephens

1 Answers

0
votes

Try this:

int **A;                        /* A points nowhere in particular */

A = malloc(sizeof(int*) * 3);   /* A points to the head of an array of int* */

A[0] = malloc(sizeof(int) * 4); /* the first element of A points to an array of int */
A[1] = malloc(sizeof(int) * 4);
A[2] = malloc(sizeof(int) * 4);

/* A can now be used as a 3x4 array */

A[2][3] = 99;
printf("%d\n", A[2][3]);

/* don't forget to tidy up */

free(A[0]);
free(A[1]);
free(A[2]);
free(A);

Don't attempt anything more complex until you have this working perfectly and understand it completely.